When implementing Views in websites, you might come across situation when you cannot find the proper field to display the data. Finally we end up using a php field for displaying the data. Use of php field will always affect the caching of the views. To avoid this we can replace this with the a custom field. To implement the same please continue reading. Add hook_views_api() to register a views api.
/**
* Implements hook_views_api().
*/
function MY_MODULE_NAME_views_api() {
return array(
'api' => 3,
'path' => drupal_get_path('module', 'MY_MODULE_NAME') . '/views',
);
}
Add hook_views_data() for registering the new field. The handler mentioned in this module is a new file which will define the functioning of the new field.
/**
* Implements hook_views_data().
*/
function MY_MODULE_NAME_views_data() {
$data['node']['custom_field_name'] = array(
'title' => t('Custom field title'),
'help' => t('Custom field description'),
'field' => array(
'handler' => 'MY_MODULE_NAME_handler_field_custom_field_name',
),
);
return $data;
}
Add a new file in the "views" folder in modules root folder with the name "MY_MODULE_NAME_handler_field_custom_field_name". Add the below contents to the new file and change the render function according to your logic.
additional_fields['type'] = 'type';
$this->additional_fields['nid'] = 'nid';
}
/**
* Called to add the field to a query.
*/
function query() {
$this->ensure_my_table();
$this->add_additional_fields();
}
/**
* Render the field.
*
* @param $values
* The values retrieved from the database.
*/
function render($values) {
$type = $this->get_value($values, 'type');
$nid = $this->get_value($values, 'nid');
return 'node' . $nid . '/' . $type;
}
}
If you are still having trouble configuring a custom field talk to a Drupal expert. Please fill in our Contact Us form and we will get back to you shortly.