0

I want to programmatically add a drop down list field to the user profile via a custom module. How do I go about adding select options for the field?

// Create Field
'suffix' => array(
  'field_name' => 'suffix',
  'type' => 'list_text',
),

//Create instance
'suffix' => array(
  'field_name' => 'suffix',
  'entity_type' => 'user',
  'label' => 'Suffix',
  'bundle' => 'user',
  'options' => array(
   '0' => 'Mr.',
   '1' => 'Mrs.',
  ),
  'widget' => array(
  'type' => 'list_text',
  );
),

The field shows up but the options do not. Anyone have a good guide they know of or tell me what I'm missing?

  • Where are your field_create_field() and field_create_instance()? These are just two arrays that have no specific meaning. Please post full code, not just arrays. – Neograph734 May 27 '16 at 22:51
3

Your available widgets for a list field are these: options_select, options_buttons and options_onoff, not list_text, that is the field type.

The widget values can be found on list_field_widget_info_alter(), where the list types are coupled with the widgets.

So I suppose you should update your field instance to use:

'widget' => array(
  'type' => 'options_select', // Drop down button or multi-select
  // OR 
  // 'type' => 'options_buttons', // Radio buttons or checkboxes.
);

The way the widget is rendered depends on the cardinality defined on your field. If cardinality is set to 1, the first type will be used (drop down or radio buttons), if cardinality > 1, you'll get a multi-select field or checkboxes.

Assuming this field can only hold one value, you should also add

'cardinality' => 1,

To your field definition.

Leaving you with:

// Create Field
$field = array(
  'suffix' => array(
    'field_name' => 'suffix',
    'type' => 'list_text',
    'cardinality' => 1,
  ),
);
field_create_field($field);


//Create instance
$instance = array(
  'suffix' => array(
    'field_name' => 'suffix',
    'entity_type' => 'user',
    'label' => 'Suffix',
    'bundle' => 'user',
    'options' => array(
     '0' => 'Mr.',
     '1' => 'Mrs.',
    ),
    'widget' => array(
      'type' => 'options_select',
    ),
  ),
);
field_create_instance($instance);
  • #Neograph734 All source code is in list_field_widget_info_alter() – Lê Quang Tú Jan 29 '18 at 2:12

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.