A
A
Alex2014-09-20 13:31:20
PHP
Alex, 2014-09-20 13:31:20

How to make a required field in a Drupal form?

Drupal has something like this

$form['type_delivery'] = array(
    '#type' => 'radios',
    '#options' => array('courier' => t('Courier'), 'other' => t('Other')),
    '#title' => t('Delivery type'),
    '#default_value' => 'courier',
  );
  $form['type_delivery_other'] = array(
    '#type' => 'textfield',
    '#title' => t('Other delivery type'),
    '#required' => true,
    '#states' => array(
      'visible' => array(
        'input[name="type_delivery"]' => array('value' =>'other'),
      ),
    ),
  );

The type_delivery_other field only appears when the type_delivery field is set to other
Question: How can I make the #required parameter dependent by analogy ? Those. if type_delivery is other then type_delivery_other is required, and if type_delivery is otherwise then type_delivery_other is NOT required.
Added on 09/30
As it turned out, the states parameter contains the property I need.
Solved the problem like this:
$form['type_delivery'] = array(
    '#type' => 'radios',
    '#options' => array('courier' => t('Courier'), 'other' => t('Other')),
    '#title' => t('Delivery type'),
    '#default_value' => 'courier',
  );
  $form['type_delivery_other'] = array(
    '#type' => 'textfield',
    '#title' => t('Other delivery type'),
    '#required' => true,
    '#states' => array(
      'visible' => array(
        'input[name="type_delivery"]' => array('value' =>'other'),
      ),
      'required' => array(
         'input[name="type_delivery"]' => array('value' =>'other'),
      ),
    ),
  );

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
andead, 2014-09-20
@andead

hover your field validator with #element_validate
https://api.drupal.org/api/drupal/developer!topics...

A
Alex, 2014-09-23
@mr_ko

You can hang an ajax handler for the type_delivery field. There are similar examples on google.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question