1

I've added a lot of fields and field instances via a custom module to some prepared content types. field_create_field() and field_create_instance() work like a charm, not a single error. Every field then works as expected, EXCEPT for the checkbox field.

It appears at the right place, has the right label, BUT when it comes to node saving the checked checkbox simply won't save. Next time I edit the node it's unchecked again, no value got written to the database. What do I miss here?

$field = array(
  'field' => array(
    'field_name'  => 'MYFIELD',
    'label'       => 'Set as default',
    'type'        => 'list_boolean',
  ),
  'instance' => array(
    'field_name'  => 'MYFIELD',
    'entity_type' => 'node',
    'bundle'      => 'MYBUNDLE',
    'label'       => 'Set as default',
    'widget'      => array(
      'type'      => 'options_onoff',
      'settings'  => array(
        'display_label' => TRUE,
      ),
    ),
    'display'     => array(
      'default'   => array(
        'label'   => 'hidden',
        'type'    => 'hidden',
      ),
    ),
  ),
);

field_create_field($field['field']);
field_create_instance($field['instance']);
2
  • 1
    Try adding 'module' => 'options', to $field['instance']['widget']. and 'module' => 'list' to $field['instance']. You're also missing 'active' => 1 and a few other things looking at it. Diff yours against this one (which works)
    – Clive
    Aug 19, 2015 at 14:04
  • @Clive - It were 'allowed_values' to $field['field]. Thanks for the pastebin!
    – leymannx
    Aug 19, 2015 at 14:30

1 Answer 1

4

Thanks @Clive, all that was missing were 'allowed_values' in $field['field]:

$field = array(
  'field' => array(
    'field_name'  => 'MYFIELD',
    'label'       => 'Set as default',
    'type'        => 'list_boolean',
    // It's mandatory to add at least two empty values here,
    // Drupal will do the rest then:
    'settings'    => array(
      'allowed_values' => array(
        '',
        '',
      ),
    ),
  ),
  'instance' => array(
    'field_name'  => 'MYFIELD',
    'entity_type' => 'node',
    'bundle'      => 'MYBUNDLE',
    'label'       => 'Set as default',
    'widget'      => array(
      'type'      => 'options_onoff',
      'settings'  => array(
        'display_label' => TRUE,
      ),
    ),
    'display'     => array(
      'default'   => array(
        'label'   => 'hidden',
        'type'    => 'hidden',
      ),
    ),
  ),
);

You simply have to declare empty On/Off values. Which may not seem too obvious, but logical at least since when you create options_onoff checkbox from the backend there's written:

On value [_____] If left empty, "1" will be used.

Off value [_____] If left empty, "0" will be used.

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.