1

I've create a custom field form widget for an entity reference field. When only one value is allowed it shows a (filtered) select list, but I want to allow user to assign multiple reference values to that field.

In my use case I want it to be shown as checkboxes when multiple values are allowed, but by default it shows my checkboxes in a 'add-another' fieldset.

How can this be accomplished?

Below some code, $type is now a field setting and is manually set.

// Construct element
$widget = $element;
$widget['#delta'] = $delta;
$type = $settings['option_limit_type'];

... extra logic ...

switch ($type) {
      case 'select':
        $widget += array(
          '#type' => 'select',
          '#prefix' => '<div id="' . $settings[$element['#field_name']]['ajax_wrapper'] . '">',
          '#suffix' => '</div>',
          '#options' => $options,
          '#delta' => $delta,
          '#element_validate' => array('_entityreference_hierachy_option_limit_validate'),
          '#default_value' =>  $saved_target_id,
        );
        break;
      case 'checkboxes':
        $widget += array(
          '#type' => 'checkboxes',
          '#prefix' => '<div id="' . $settings[$element['#field_name']]['ajax_wrapper'] . '">',
          '#suffix' => '</div>',
          '#options' => $options,
          '#delta' => $delta,
          '#element_validate' => array('_entityreference_hierachy_option_limit_validate'),
          '#default_value' =>  $saved_target_id,
        );
        break;
    }
return $widget;
0

You can use drupal form api attributes like


 case 'select':
        $widget += array(
          '#type' => 'select',
          '#prefix' => '<div id="' . $settings[$element['#field_name']]['ajax_wrapper'] . '">',
          '#suffix' => '</div>',
          '#options' => $options,
          '#delta' => $delta,
          '#element_validate' => array('_entityreference_hierachy_option_limit_validate'),
          '#default_value' =>  $saved_target_id,
          '#multiple' => $multiple,
          '#size' => $multiple ? min(12,count($options)) : 0, 
        );
        break;

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#multiple

0

In hook_field_widget_info() use 'FIELD_BEHAVIOR_CUSTOM' like this:

 'field_my_checkboxes' => array(
  'label' => t('Let the user select from a set of checkboxes.'),
  'field types' => array('field_myfield'),
  'behaviors' => array(
    'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  ),

In this case 'Add another' link and fieldset won't be shown but you need to handle user's input manually. Example: https://www.drupal.org/node/1464770

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.