2

I need to loop through all the values of a multi field as per example bellow:

for ($i = 1; $i < ???; $i++) {

    $a = $form['field_...']['und'][$i]['#entity']->field_...['und'][0]['value'];  

}

of course I could do something like this

foreach ($form['field_additional_sections']['und'] as $key=>$value) {
if (is_int($key)) {
.... }
}

but I was wondering if there is a nicer option to do this. I should probably mention that I'm implementing hook_FORM_ID_form_alter.

Thank you

1 Answer 1

3

element_children() is the easiest way to get a list of all child elements in a render array, e.g.

foreach (element_children($form['field_...'][LANGUAGE_NONE]) as $key) {
  $element = $form['field_...'][LANGUAGE_NONE][$key];
}
4
  • Why not a simple count($form['field_...'][LANGUAGE_NONE]) ? Aug 27, 2013 at 9:01
  • @GregoryKapustin I need to loop through all the values of a multi field...can't do that with a count :)
    – Clive
    Aug 27, 2013 at 9:13
  • I was thinking about for ($i = 1; $i < count(...); $i++) { Aug 27, 2013 at 9:41
  • 4
    @GregoryKapustin The actual children are mixed with FAPI-specific array items. I.e. the items which has keys starting with a # sign. element_children solves that specific problem by checking if the first character of the array key is a #.
    – hampusn
    Aug 27, 2013 at 9:47

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.