Code Snippets

Using PHP on Drupal views fields

In this post, it will explain how to provide your own custom field to views. For more in depth information, click on this link.

Using an example module called appnovation_fillout_viewsfield, we just write:

1
2
3
4
5
6
7
8
9
10
<?php
/**
 * Implements hook_views_api().
 */
function appnovation_fillout_viewsfield_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module''appnovation_fillout_viewsfield') . '/views',
  );
}

 Then implement hook_views_data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
/**
 * Implements hook_views_data().
 */
function appnovation_fillout_viewsfield_views_data() {
  $data array();
  $data['node']['fillout'] = array(
    'title' => t('Fillout field'),
    'help' => t('Will display a link to node edit ONLY if any of the current row\'s listed fields is empty.'),
    'field' => array(
      'handler' => 'appnovation_fillout_viewsfield_handler_fillout',
    ),
  );
  return $data;
}

 Lastly, writing the handler. For this example, we will create a file named appnovation_fillout_viewsfield_handler_fillout.inc:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
/**
 * @file
 * Definition of appnovation_fillout_viewsfield_handler_fillout.
 */
 
/**
 * Provides a field which will display a link to edit the node if any other listed fields are empty.
 */
class appnovation_fillout_viewsfield_handler_fillout extends views_handler_field_node_link_edit {
  /**
   * Override views_handler_field_node_link_edit::render_link()
   */
  function render_link($node$values) {
    // Get all field handlers on this display
    $fields $this->view->display_handler->get_handlers('field');
    // Check if ANY field is empty
    foreach($fields as $key => $field) {
      // ignore our field (duh)
      if ($key !== 'fillout') {
        if (empty($field->get_value($values))) {
          // Let the views hanlder provide the link, it checks for access etc ;)
          return parent::render_link($node$values);
        }
      }
    }
  }
 
}

 

Resource Tags: