7

I want to add new field in a existing view programmatically.

I am trying to use hook_views_pre_render().

function registration_export_views_pre_render(&$view) {
    if ($view->name=='registrations_export') {
        foreach($view->result as $r => $result) {
        //dpm($result->registration_id);
        $result->registration_id = 1;   
        }
    }

}

If i add the "registration id" field to view page then i can see registration id field in my output. But i dont want to add in view field add page. I want to field add dynamically.

As per suggestion i have tried this

    function registration_export_views_pre_view(&$view, &$display_id, &$args) {
          if ($view->name == 'registrations_export') {
            views_db_object::add_item($view->current_display, 'field', 
    'field_data_field_first_name_1', 'field_first_name_1', 
$options = array(
            $handler->display->display_options['fields']['field_first_name_1']['id'] = 'field_first_name_1',
            $handler->display->display_options['fields']['field_first_name_1']['table'] = 'field_data_field_first_name_1',
            $handler->display->display_options['fields']['field_first_name_1']['field'] = 'field_first_name_1',

            ), $id = NULL);


          }
        }

View export

$view = new view();
$view->name = 'registrations_export';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'registration';
$view->human_name = 'registrations_export';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'List of Event Registrations';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'title',
    'rendered' => 1,
    'rendered_strip' => 1,
  ),
);
$handler->display->display_options['style_options']['columns'] = array(
  'registration_id' => 'registration_id',
  'nid' => 'nid',
  'title' => 'title',
  'field_first_name_1' => 'field_first_name_1',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'registration_id' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'nid' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'title' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_first_name_1' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Registration: Registration to Node */
$handler->display->display_options['relationships']['registration_related_node']['id'] = 'registration_related_node';
$handler->display->display_options['relationships']['registration_related_node']['table'] = 'registration';
$handler->display->display_options['relationships']['registration_related_node']['field'] = 'registration_related_node';
/* Field: Field: Salutation */
$handler->display->display_options['fields']['field_salutation_new']['id'] = 'field_salutation_new';
$handler->display->display_options['fields']['field_salutation_new']['table'] = 'field_data_field_salutation_new';
$handler->display->display_options['fields']['field_salutation_new']['field'] = 'field_salutation_new';
$handler->display->display_options['fields']['field_salutation_new']['exclude'] = TRUE;
/* Field: Field: State */
$handler->display->display_options['fields']['field_state']['id'] = 'field_state';
$handler->display->display_options['fields']['field_state']['table'] = 'field_data_field_state';
$handler->display->display_options['fields']['field_state']['field'] = 'field_state';
$handler->display->display_options['fields']['field_state']['exclude'] = TRUE;
/* Field: Field: Payment Type */
$handler->display->display_options['fields']['field_payment_type']['id'] = 'field_payment_type';
$handler->display->display_options['fields']['field_payment_type']['table'] = 'field_data_field_payment_type';
$handler->display->display_options['fields']['field_payment_type']['field'] = 'field_payment_type';
/* Field: Global: PHP */
$handler->display->display_options['fields']['php']['id'] = 'php';
$handler->display->display_options['fields']['php']['table'] = 'views';
$handler->display->display_options['fields']['php']['field'] = 'php';
$handler->display->display_options['fields']['php']['use_php_setup'] = 0;
$handler->display->display_options['fields']['php']['php_output'] = '<?php 
//echo \'<pre>\';
//print_r($view->result[0]->_field_data[\'registration_id\'][\'entity\']);
//print_r($data);
//print_r($row->title);
?>';
$handler->display->display_options['fields']['php']['use_php_click_sortable'] = '0';
$handler->display->display_options['fields']['php']['php_click_sortable'] = '';
/* Filter criterion: Content: Title */
$handler->display->display_options['filters']['title']['id'] = 'title';
$handler->display->display_options['filters']['title']['table'] = 'node';
$handler->display->display_options['filters']['title']['field'] = 'title';
$handler->display->display_options['filters']['title']['relationship'] = 'registration_related_node';
$handler->display->display_options['filters']['title']['operator'] = 'contains';
$handler->display->display_options['filters']['title']['exposed'] = TRUE;
$handler->display->display_options['filters']['title']['expose']['operator_id'] = 'title_op';
$handler->display->display_options['filters']['title']['expose']['label'] = 'Event Name';
$handler->display->display_options['filters']['title']['expose']['operator'] = 'title_op';
$handler->display->display_options['filters']['title']['expose']['identifier'] = 'title';
$handler->display->display_options['filters']['title']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
  5 => 0,
  7 => 0,
  9 => 0,
  10 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'registrations-list';

/* Display: Data export */
$handler = $view->new_display('views_data_export', 'Data export', 'views_data_export_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '0';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'views_data_export_csv';
$handler->display->display_options['style_options']['provide_file'] = 1;
$handler->display->display_options['style_options']['filename'] = '%timestamp-dd - %timestamp-mmm %view.csv';
$handler->display->display_options['style_options']['parent_sort'] = 0;
$handler->display->display_options['style_options']['quote'] = 1;
$handler->display->display_options['style_options']['trim'] = 0;
$handler->display->display_options['style_options']['replace_newlines'] = 0;
$handler->display->display_options['style_options']['header'] = 1;
$handler->display->display_options['style_options']['keep_html'] = 0;
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Content: Title */
$handler->display->display_options['filters']['title']['id'] = 'title';
$handler->display->display_options['filters']['title']['table'] = 'node';
$handler->display->display_options['filters']['title']['field'] = 'title';
$handler->display->display_options['filters']['title']['relationship'] = 'registration_related_node';
$handler->display->display_options['filters']['title']['operator'] = 'contains';
$handler->display->display_options['filters']['title']['exposed'] = TRUE;
$handler->display->display_options['filters']['title']['expose']['operator_id'] = 'title_op';
$handler->display->display_options['filters']['title']['expose']['label'] = 'Event Name';
$handler->display->display_options['filters']['title']['expose']['operator'] = 'title_op';
$handler->display->display_options['filters']['title']['expose']['identifier'] = 'title';
$handler->display->display_options['filters']['title']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
  5 => 0,
  7 => 0,
  9 => 0,
  10 => 0,
);
$handler->display->display_options['path'] = 'registrations-list-export-csv';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);

/* Display: Data export 2 */
$handler = $view->new_display('views_data_export', 'Data export 2', 'views_data_export_2');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['style_plugin'] = 'views_data_export_xls';
$handler->display->display_options['style_options']['provide_file'] = 1;
$handler->display->display_options['style_options']['parent_sort'] = 0;
$handler->display->display_options['path'] = 'registrations-list-export-xls';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);

Thank you very much.

6
  • 1
    Your example code is just adding a hard coded value. Is that what you want to do or do you want to properly add a field so it acts the same as if it was added via the UI?
    – rooby
    Oct 25 '14 at 9:04
  • @rooby thanks for reply, you are right i wants to add field dynamically and it acts the same as if it was added via the UI.
    – Tushar
    Oct 25 '14 at 10:03
  • What is the reason for needing to add the field programmatically? In my experience that is not a common request and there may be a better way to accomplish what you want to do.
    – rooby
    Oct 25 '14 at 13:06
  • i am using entity registration module for node registration. And trying to export participant list using view export module but the registration field not same for all field as we can create multiple registration form. So i think dynamically add field to view.
    – Tushar
    Oct 25 '14 at 13:11
  • There are a couple of alternatives (although maybe they are not suitable for your requirements): Use the same fields for different registration forms or include all fields in your view and the ones that are not relevant to certain forms will just be empty.
    – rooby
    Oct 25 '14 at 13:53
15

Check out the function views_db_object::add_item().

There is an example at https://drupal.stackexchange.com/a/70649/10729 of using it to add header/footer items but it can be used for fields too.

Where your code goes depends on your situation but I would suggest that the pre_render hook is too late because the sql has already been executed and you need to add the field before that happens or you won't get the data.

A better example for what you want to do is at http://dropbucket.org/node/1178

In case that link goes away the code is:

/**
 * Implements hook_views_pre_view().
 *
 * Add 'Custom text' field.
 */
function hook_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'my_view') {
    $view->add_item($view->current_display, 'field', 'views', 'nothing', array(
      'label' => 'My field',
      'alter' => array('text' => 'My field text'),
      'element_class' => 'my-field',
      'element_default_classes' => 0,
    ), 'my_field');
  }
}

If you want to know how to construct the array for the field settings I suggest creating a view via the UI with a field the way you want it, then export the view and see how it outputs that field. You can use that info to create your field array.

[EDIT] Your current attempt at using the add_item() function isn't working because you are passing in the wrong parameters for what you want to do.

If you look at the linked documentation for add_item() it shows what it expects for the parameters (admittedly in this case the docs aren't very good but the parameter names help).

The function definition looks like this:

views_db_object::add_item($display_id, $type, $table, $field, $options = array(), $id = NULL)

So you are passing in:

  • $display_id: The current display - which is fine.
  • $type: "field" - which is fine.
  • $table: "views" - this is almost certainly not right. The views table is for special views fields like "Custom text" (which is what that example is adding as per its comment). You need to pass in the table name for the field you want to add. For example if you wanted to add the nid field the table would be "node". If you have a field called field_firstname then you would probably want the table "field_data_field_firstname".
  • $field: "nothing" - this is also probably not right. Again the nothing field is the views "Custom text" field. to go with my table examples would be something like "nid" or "field_firstname".
  • $options: This is likely not right either as it is a copy of the custom text field example with changed values, however the field you want to add probably requires different options to the custom text field. As mentioned before, the best way to work out what to add here is to create a view with the field you want to add set up the way you want it, then export the view and it will give you the settings. for example here is part of a view export for a field:

    /* Field: Content: Contact Email */
    $handler->display->display_options['fields']['field_contact_email']['id'] = 'field_contact_email';
    $handler->display->display_options['fields']['field_contact_email']['table'] = 'field_data_field_contact_email';
    $handler->display->display_options['fields']['field_contact_email']['field'] = 'field_contact_email';
    $handler->display->display_options['fields']['field_contact_email']['label'] = '';
    $handler->display->display_options['fields']['field_contact_email'] ['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['field_contact_email']['type'] = 'email_spamspan';
    

    You can see it gives information about table, field, id and other settings which you can use when you are adding your field programmatically.

So compare the values in this array (read the array values, don't just copy and paste, it will help make sense of the array structure) using this field as an example your options would be something like this:

array(
  'label' => '',
  'element_label_colon' => FALSE,
  'type' => 'email_spamspan',
)

But there are lots of possible options depending on the field type you are using. You can also try with an empty options array at first too.

The views export is full of square bracket array syntax so it converts easily into an array (for more information see http://php.net/manual/en/language.types.array.php#language.types.array.syntax.accessing).

Programmatically modifying views can get pretty complex so I recommend a lot of reading of PHP docs, Drupal docs, and Views docs. Copy & paste will only get you so far.

13
  • as per your suggestion i have tried the code but i think i am missing some where can you please look my updated code. Also i have checked by export the view. But not getting the array like above.
    – Tushar
    Oct 25 '14 at 10:55
  • I have updated my answer. The exported view won't give you the exact array you need to pass in but it helps with keys and values. Another thing you can do is install the devel module and do a dpm($view) or dpm($view->fields) or something along those lines to see the fields in a better array structure. That will probably help more than the view export.
    – rooby
    Oct 25 '14 at 11:19
  • Thanks @rooby, actually this is new for me. one more question the function definition (views_db_object::add_item($display_id, $type, $table, $field, $options = array(), $id = NULL)) can i write inside hook_views_pre_view() or how i call this function?
    – DRUPWAY
    Oct 25 '14 at 11:30
  • The example hook_views_pre_view() in my answer and in the question are accurate but you can call it anywhere you have the $view object by doing $view->add_item(); It generally needs to be called before the view runs or else there is no point adding the item. The other stack exchange answer I linked to can be done from anywhere as it loads a view, then adds an item, then executes the view. If you're not manually executing the view then hook_views_pre_view() is a good place for it.
    – rooby
    Oct 25 '14 at 11:37
  • 1
    Good question and answer. The docs for views_db_object::add_item linked to in answer has a comment by @jnicola that describes using get_items() and get_item() to get to the options. Oct 25 '14 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.