0

First of all let me say that this is my first project in Drupal and I am still confused, I apologize if my question is stupid.

I created a custom entity in Drupal 7 using Entity API. The custom entity represents a golf course.

I used this tutorial: http://www.sitepoint.com/series/build-your-own-custom-entities-in-drupal/ Then I tried to add a custom theme, to do so I followed this: https://www.drupal.org/node/1238606

My callback function looks like this:

function view_my_entity($id) {
  $entities = entity_load('my_entity_type', array($id));
  $entity = $courses[$id];
  drupal_set_title($entity->name);
  $output = entity_view('my_entity_type', array($entity));
  $output += array(
    '#theme'     => 'my_theme',
    '#element'   => $output,
    '#view_mode' => 'full',
    '#language'  => LANGUAGE_NONE,
  );
  return $output;
}

And this is my hook_theme():

function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my_theme' => array(
      'variables' => array('element' => null),
      'template' => 'my_template',
    ),
  );
}

The problem is that in my_template.tpl.php I can only access the golf course variables this way (in this example I will access the address):

render($element['my_entity_type']['The Name of my Entity']['address']['#markup'])

As you can see, in order to access the address I have to use 'The Lakes Golf Club', (which is the name of the currently displayed golf course), as a key, but obviously that name is going to change every time I display a different golf course, so my question is:

How can I access the golf course attributes without having to use the golf course name as a key?

EDIT

the docs for entity_view() (http://www.drupalcontrib.org/api/drupal/contributions!entity!entity.module/function/entity_view/7) say the following:

Return value

The renderable array, keyed by the entity type and by entity identifiers, for which the entity name is used if existing - see entity_id(). If there is no information on how to view an entity, FALSE is returned.

So how do I avoid that the array is keyed by the name of the entity? If it was keyed by the id it would be OK because I have the $id variable in scope.

1 Answer 1

0

This can be easily solved by including this snippet at the beginning of your template file:

// my_template.tpl.php
<?php
$keys = array_keys($element['my_entity_type']);
$my_entity_name = $keys[0];
$my_entity = $element['my_entity_type'][$my_entity_name];
?>

Now you can easily print values like so:

<?php print render($my_entity['address']['#markup']); ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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