4

I've a term reference multi value field. What is the right way to count filled values which is also portable to D8, D9 etc.

The dsm output shows like this:

enter image description here

2
  • Are you just trying to count the number of items in a $node->field_name, or are you trying to count the inputted values during form validation/submit?
    – hargobind
    Commented Oct 26, 2013 at 8:00
  • I mean whenever hook_form_alter is called, I need to count the values.
    – AgA
    Commented Oct 26, 2013 at 11:29

3 Answers 3

1
$wrapper = entity_metadata_wrapper('entity_type', $entity);
dpm($wrapper->{FIELD_NAME}->count());

Dealing with entity reference field you can get the identifires like this:

dpm($wrapper->{FIELD_NAME}->value(array('identifier' => TRUE)));
3
  • $wrapper->{FIELD_NAME}->count() method doesn't exists.
    – D34dman
    Commented Nov 5, 2015 at 9:24
  • Just use it, It does exist. Also the dpm($wrapper->{FIELD_NAME}->value(array('identifier' => TRUE))); is good to get all ids from a multivalue field taxonomy reference Commented Apr 6, 2017 at 14:41
  • Out of interest, I tested the ->count() it and it works fine. Commented Apr 16, 2017 at 6:05
1

Using Entity Metadata Wrapper, you can achieve it this way.

$wrapper = entity_metadata_wrapper('node', $node);
$count = count($wrapper->{FIELD_NAME});
0

It really depends on the type of field, and on when you are trying to retrieve the values.

During hook_form_alter() for checkboxes, radios, and select fields, the values you are referring to are typically set via the #options property. Example: $form['artist_tags']['und']['#options']. You can wrap that in count() to get the number of values.

During hook_form_validate() or hook_form_submit() or a function called from the $form['#after_build'] property, you will also have access to the number of selected values via $form_state['values']['artist_tags']['und'] (or when $form_state['submitted'] is TRUE, check $form_state['input']['artist_tags']['und']).

Your Answer

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

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