jquerydrupalcustom-listsdrupal-8

drupal 8 conditional field


I want to add province and city fields to user entity in drupal 8. by changing province, list of cities should be updated. in drupal 7 I've done this with conditional field module, but this module isn't ready for drupal 8 yet. what is the right way to do this in drupal 8? should I add fields and then add jquery to my registration template for doing this or is there a better and standard way to do this. thank you.


Solution

  • With a little bit of (PHP) code, it's possible to use Drupal's states processing to explicitly say which fields should be shown or hidden given which conditions.

    For example, this shows design type, design location, and design discipline fields when Design (term ID 4) is selected in the category field, etc:

    /**
     * Implements hook_form_alter().
     *
     * On Work node add and edit, set only selected category's associated
     * vocabularies as visible.
     */
    function mass_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
      if ($form_id != 'node_work_form' && $form_id != 'node_work_edit_form') {
        return;
      }
      if (isset($form['field_category'])) {
        $states_when_category_is_design = array(
          'visible' => array(
            ':input[name="field_category"]' => array('value' => '4'),
          ),
        );
    
        $states_when_category_is_advocacy = array(
          'visible' => array(
            ':input[name="field_category"]' => array('value' => '19'),
          ),
        );
    
        $states_when_category_is_research = array(
          'visible' => array(
            ':input[name="field_category"]' => array('value' => '25'),
          ),
        );
    
        if (isset($form['field_design_type'])) {
          $form['field_design_type']['#states'] = $states_when_category_is_design;
        }
    
        if (isset($form['field_design_location'])) {
          $form['field_design_location']['#states'] = $states_when_category_is_design;
        };
    
        if (isset($form['field_design_discipline'])) {
          $form['field_design_discipline']['#states'] = $states_when_category_is_design;
        };
    
        if (isset($form['field_advocacy_type'])) {
          $form['field_advocacy_type']['#states'] = $states_when_category_is_advocacy;
        };
    
        if (isset($form['field_research_type'])) {
          $form['field_research_type']['#states'] = $states_when_category_is_research;
        };
      }
    }
    

    (This code is shamelessly stolen from Mauricio Dinarte aka dinarcon, my colleague and fellow worker-owner at Agaric.)