How to create an Add Button programmatically

Last updated on
13 March 2019

In certain situations, you will want to add an Add Button to a view programmatically, typically in a case such as installing a module, and modifying a view so that it will append an add button for a content type you are creating. You may do so using this snippet in a hook_install function in your module's .install file.

Replace any {my_} references with your relevant view/entity information

$storage_config = \Drupal::configFactory()->getEditable('views.view.{my_view}');
  $settings = $storage_config->getOriginal('display');
  $settings['default']['display_options']['header']['{my_add_button}'] = array(
    'id' => 'views_add_button',
    'table' => 'views',
    'field' => 'views_add_button',
    'relationship' => 'none',
    'group_type' => 'group',
    'admin_label' => '',
    'empty' => TRUE,
    'tokenize' => TRUE,
    'type' => '{my_entity}+{my_entity_type}',
    'context' => '',
    'button_text' => '{my_text}',
    'button_classes' => '{my_button_classes}',
    'button_attributes' => '',
    'button_prefix' => [
      'value' => '',
      'format' => 'basic_html',
    ],
    'button_suffix' => [
      'value' => '',
      'format' => 'basic_html'
    ],
    'query_string' => '',
    'destination' => TRUE,
    'plugin_id' => 'views_add_button_area',
  );
  $storage_config->set('display', $settings)->save();

Help improve this page

Page status: No known problems

You can: