1

I have $host_entity which contains:

field_eventorganizer (Array, 1 element)
und (Array, 3 elements)
0 (Array, 1 element)
target_id (String, 2 characters ) 20
1 (Array, 1 element)
target_id (String, 4 characters ) 345
2 (Array, 1 element)
target_id (String, 2 characters ) 678

and the below code in which I need to create multiple arrays inside the array('#markup'.

$organisers=user_load($host_entity->field_eventorganizer['und'][0]['target_id']);
$organiser_email=$organisers->mail;
    $build['field_eventorganizer'] = array(
    '#theme' => 'registration_property_field',
    '#label' => 'Event Organiser(s)',
    '#items' => array(
        array('#markup' => l($username, 'mailto:' . $organiser_email, array('absolute' => TRUE)),),
        ),
        '#classes' => 'field field-label-inline clearfix',
    );

Do I need to create a foreach loop after array('#markup' => ?

0

Try this to loop the $build variable :)

// define variables
$organisers[] = "";
$organiser_email = "";
$organiser_name = "";
$email_delimiter = "; ";

// recreate the array from your example
$organisers['und'][0]['target_id'] = 20;
$organisers['und'][1]['target_id'] = 345;
$organisers['und'][2]['target_id'] = 678;

// populate $build variable
$build['field_eventorganizer'] = array(
      '#theme' => 'registration_property_field',
      '#label' => 'Event Organiser(s)2',
      '#classes' => 'field field-label-inline clearfix',
    );

// because the numbers are nested in the array, I've chosen to use `for` instead of 
// `foreach` to use $i as the iterator then rebuild what I'm looking for in the loop. I've 
// used count($organisers['und']) because the next piece of the array is the number we are
// using to load user data.

for ($i = 0; $i < count($organisers['und']); $i++) {
    // load the user object based on $i
    $organisers = user_load($host_entity->field_eventorganizer['und'][$i]['target_id']);
    // fetch loaded users email
    $organiser_email = $organisers->mail;
    // fetch loaded users name
    $organiser_name = $organisers->name;
    // populate $build variable
    $build['field_eventorganizer'][] = array(
      '#items' => array(
        array('#markup' => l($organiser_name, 'mailto:' . $organiser_email, array('absolute' => TRUE)),),
      ),
    );
}

Side note: Not sure if it was intentional or not, but be careful of your plurals. You are using $organisers and $organiser_email which can sometimes be missed and cause a headache.

| improve this answer | |
  • 1
    As discussed, thanks again as always you rock! I learned tons, and would have used foreach loop instead lol Grat point about wording and plural! – Markus Jun 20 at 8:10

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.