0

I have a content type with one paragraph field which has a checkbox and a text field.

By default, the text field is optional. I want to make it required when the checkbox is checked. Conditional fields module does not work with paragraphs properly. I tried with #states, but this just adds a class. It doesn't make the field required in the back-end.

Maybe I should write a custom validation. How can add it for paragraph field with two fields inside?

2

As you mentioned, you'll need to add a custom validate function. Since this checkbox can be checked or unchecked on the fly, you will also need to use some javascript to toggle the "required" class on and off the textbox. This will make sure it looks right to the user. Of course you'll need to make sure you have a required class style in css.

This is just freehand, and just one way it could be done. You would need to adapt this to your fields.

create a custom module. In your .module file

<?php
use Drupal\Core\Form\FormStateInterface;

function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  //where CONTENTTYPE is the machine name of your content type
  if ($form_id == 'node_CONTENTTYPE_edit_form') {
    $form['#validate'][] = 'my_test_validate';
  }
}

function my_test_validate($form, FormStateInterface &$form_state) {
  $checkbox = $form_state->getValue('field_my_checkbox');
  $textfield = $form_state->getValue('field_my_textbox');

  //if the checkbox is checked
  if ($checkbox['value'] == 1) {
    if (trim($textfield[0]['value']) == "" || empty($textfield)) {
      $form_state->setErrorByName('mytextfield', t('Text field blah blah is required'));
    }
  }
}

In a js file somewhere in your module or theme you could have something like:

(function ($, Drupal) {

  Drupal.behaviors.myForms = {
    attach: function (context, settings) {
      //add a click listener to toggle whatever styles you want
      $('#edit-field-mycheckbox-value').click(function(){
        $('#edit-my-textfield-0-value').toggleClass('required');
        $("label[for='edit-my-textfield-0-value']").toggleClass('form-required');
      //etc
      });


    }
  };

})(jQuery, Drupal);
  • Thank you! This is working but how can I check/add this validation only for one paragraph type. If I have 3 paragraph types inside with some reusable fields in $form_state->getValues() I will have the same fields. – user3421014 Oct 25 '18 at 8:39

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.