0

I am using drupal 7:

$form['title']['#tree'] = TRUE;
$form['title']['node_first'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
        'value' => $value->title,
    ),
);
$form['title']['node_second'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
        'value' => $value2->title,
    ),
);

i am getting this output after submitting (when first checkbox has been checked) :

    Array
(
    [title] => Array
        (
            [node_first] => Array
                (
                    [value] => value
                )

            [node_second] => Array
                (
                    [value] => 0
                )

        )
)

desired output:

Array
(
    [title] => Array
        (
            [node_first] => Array
                (
                    [value] => True
                )

            [node_second] => Array
                (
                    [value] => False
                )

        )
)
1
  • 2
    Drupal won't do that for you; just cast the value to a bool if you need one
    – Clive
    Commented Jun 5, 2019 at 11:20

2 Answers 2

0

It should be possible to manipulate the values as desired in a custom validate function. In your form code, add something like this:

$form['#validate'][] = 'mymodule_custom_validate';

The mymodule_custom_validate is a function you could define as such to change the values to booleans, or anything else you need:

function mymodule_custom_validate(&$form, &$form_state) {
  if ($form_state['values']['title']['node_first']['value'] === 'value') {
    $form_state['values']['title']['node_first']['value'] = True;
  }
  else {
    $form_state['values']['title']['node_first']['value'] = False;
  }
  if ($form_state['values']['title']['node_second']['value'] === 'value') {
    $form_state['values']['title']['node_second']['value'] = True;
  }
  else {
    $form_state['values']['title']['node_second']['value'] = False;
  }
}

This is a fairly rudimentary implementation, but hopefully this will lead you in the right direction. You can see in this example how the values can be manipulated before they reach the submit handler.

0

Surely a single checkbox would be better?

$form['title']['#tree'] = TRUE;
$form['title']['node_first'] = array(
    '#type' => 'checkbox',
    '#title' => $value->title,
);
$form['title']['node_second'] = array(
    '#type' => 'checkbox',
    '#title' => $value2->title,
);

Form API Reference

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.