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_golf_course($id) {
$courses = entity_load('golf_course', array($id));
$course = $courses[$id];
drupal_set_title($course->name);
$output = entity_view('golf_course', array($course));
$output += array(
'#theme' => 'golf_course',
'#element' => $output,
'#view_mode' => 'full',
'#language' => LANGUAGE_NONE,
);
return $output;
}
And this is my hook_theme()
:
function golf_course_theme($existing, $type, $theme, $path) {
return array(
'golf_course' => array(
'variables' => array('element' => null),
'template' => 'golf_course',
),
);
}
The problem is that in golf_course.tpl.php
I can only access the golf course variables this way (in this example I will access the address):
render($element['golf_course']['The Lakes Golf Club']['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?
The documentation for entity_view()
says:
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.
For anyone looking for an answer to this question: if the result set of the query contains multiple rows, then entity_view will create an array with an empty index like so:
$element['golf_course']['']
and now you can access all entity fields of all rows in the result set by accessing the ['#entity']
array like so:
$element['golf_course']['']['#entity'] // all golf courses
$element['golf_course']['']['#entity'][0] // first golf course in the result set
$element['golf_course']['']['#entity'][0]['label'] // label of first golf course
$element['golf_course']['']['#entity'][0]['address'] // address of first golf course
On a side note, if your templates are in pure PHP you can just avoid using entity_view()
, you will get a cleaner array (you don't have the ['golf_course']['']['#entity']
part).