2

I'm sure there is a function to help with this by I can't find it in the API docs. What I want to do is: in a hook_form_alter, iterate over all of an element's items and and manipulate them.

The example form below is from a bean form which has a multivalue field collection called field_listing_articles. I want to iterate over all the instances of that element. They are located in the form under field_listing_articles -> und -> 0, 1, 2 etc

If I do a foreach and iterate over $form['field_listing_articles'][LANGUAGE_NONE] I will pick up all the other (non-numeric) parts of the form at that level. I realise I could put an if is_numeric condition in there but I'm sure there is a more 'Drupal' way of doing this.

Any advice appreciated.

$form    
--label  
--title  
--view_mode  
--bean  
--actions  
--#validate  
--#submit  
--#parents  
--#entity  
--field_listing_articles  
----#type  
----#attributes  
----#weight  
----#tree  
----#language  
----und  
------0  
------1  
------2  
------3  
------4  
------5  
------6  
------#theme  
------#field_name  
------#cardinality  
...etc  
  • 1
    So far I've found the function element_children which looks like it will do the trick. Example code: $children = element_children($form['field_listing_articles'][LANGUAGE_NONE]); foreach ($children as $delta) { // Do manipulation here. } – tanc Sep 30 '12 at 7:43
1

element_children() returns any array's key that doesn't start with #, used for properties in form API arrays, and in rendering arrays. It doesn't return numeric keys, as the function would pass to your code an array key such as "item", for example.

Instead of using the constant LANGUAGE_NONE, I would use field_get_items(), which returns the values for the language currently set for the field, which could not be for the LANGUAGE_NONE language.

  • "It doesn't return numeric keys" - could you clarify? If I have a form element under $form['something'][$numeric_id] it will be omitted? Function's code does not look like it would. – Mołot Jul 4 '13 at 10:38

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.