1

In a Views field handler, one can define additional fields to accompany the base field defined in hook_field_data. These field values are based on database columns on the same row, and they can be used in the render function. Somewhat like this:

my_views_field_handler extends views_handler_field {

  function construct() {
    parent::construct();
    $this->additional_fields['property2'] = 'property2';
  }

  function render($values) {
    return $this->get_value($values) . $this->get_value($values, 'property2');
  }

}

But is it also possible to define a join in the constructor? One of my database columns is an id of another entity. I have been using it somewhat like this, but this generates quite a lot of overhead (loading an entire entity for each row).

  function render($values) {
    $id = $this->get_value($values, 'property2');
    $entity = entity_load_single('my_type', $id);

    if ($entity->some_other_field == TRUE) {
      return $this->get_value($values);
    }
    else {
      return 'none';
    }
  }

So is there something like a join I can use in the constuctor, so I can query the other entity table directly instead of having to load the entity?

1
+100

Yes, but you need to have already defined that relationship in the view. Per the docs for views_handler_field::add_additional_fields($fields):

@param $fields
An array of fields. The key is an identifier used to later find the field alias used. The value is either a string in which case it's assumed to be a field on this handler's table; or it's an array in the form of
@code array('table' => $tablename, 'field' => $fieldname) @endcode

Thus, say you had a field handler for a field on the node table with a defined author relationship to the users table. You could do this:

  function construct() {
    parent::construct();
    $this->additional_fields['mail'] = array(
      'table' => 'users',
      'field' => 'mail',
    );
  }

Which would allow you to do this:

function render($values) {
  //Get the mail column from the users table.
  $this->get_value($values, 'mail');
}

For your case, you'll need to define the entity relationship to your base table before you can do this.

  • Yes, I do remember reading something like this in the past. I'll try it later today :) – Neograph734 May 27 '16 at 8:16
  • This did it, bounty unlocks in a few more hours. – Neograph734 May 27 '16 at 12:11

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.