2

I'm creating an entity in code using the eck. I've added both properties and fields to my custom entity. That is working great, except I can't figure out how to display certain entity properties when hook_entity_view is being called?

I have this in a custom module -

function mycustommodule_entity_view_alter($build, $type){
  if ($type == 'mycustomentity'){


  }

}

It's suppose to take a render array, but there is no $entity->content and I've tried various things to add a very simple render array #markup => 'somemarketup'; to $build, but I have not been successfully. Given that my property is named something like 'myproperty' and is just a text property (from eck) can someone help me with the syntax for adding it to the entity display using hook_entity_view_alter?

4

Accessing the entity

hook_entity_view_alter does not have an $entity parameter. This is a problem that has been addressed in Drupal 8 (see https://drupal.org/node/1618140).

In the mean time you can't be certain that the entity is available, because it depends on the function that invokes hook_entity_view_alter in the first place. Anyone can invoke hook_entity_view_alter, any may (or may not) provide you with the entity in the build array.

The EntityApiController from the entity module (which is not core, but is a requirement for eck) adds a '#entity' field to the build array which contains the entity. My feeling is that it should be safe in most cases to rely on this, but you can't be 100% sure that it will be there.

Here is an example, assuming a required field 'field_mycustomfield' which has a 'value' property (eg. simple text field):

function mycustommodule_entity_view_alter(&$build, $type){
  if ($type == 'mycustomentity' && isset($build['#entity'])){
    $value = field_get_items($type, $entity, 'field_mycustomfield');
    $build[] = array(
      '#type' => 'markup',
      '#markup' => "My custom value: " . check_plain($value[0]['value']
    );      
  }
}

Adding values to the build array

You have a small mistake in your code: to be able to modify the $build parameter, you must take that parameter by reference (as showed on the documentation for hook_entity_view_alter). Look at my example above and notice the & before $build.

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.