-1

I have an image field and a checkbox in my node edit form. I want the image field to be required when the checkbox is not checked. And I want the image field to not be required when the checkbox is checked.

How can I do this?

4
  • Does this answer your question: How can I make a form element required with states?
    – leymannx
    Commented Sep 9, 2021 at 8:33
  • So using #states to make a field required is not possible. I should figure out a way to create my own validation. Thanks
    – Joost
    Commented Sep 9, 2021 at 13:22
  • #states to make a field required is possible, and it's easy. But it requires JS, and validation will be done in the browser. If that works for you, because your whole site won't work without JS, cool. Alternatively you'd implement an #element_validate callback and do the validation in PHP. Depends a bit on how important the form and the requirement is.
    – leymannx
    Commented Sep 9, 2021 at 15:17
  • @leymannx JS validation is fine for the use case I'm working on. But how can I make this work for an image field?
    – Joost
    Commented Sep 13, 2021 at 7:25

1 Answer 1

1

For image field use #states, this will be making a field required based on the checkbox clicked or not. Check here for more information

'#states' => array(
  'required' => array(
    :input[name="NAME OF THE FIELD"]' => array('value' => 'VALUE OF FIELD'),
  ),
),
3
  • Thanks this already helped out a lot. I have one question though. At this part of the link you provided they say that required is a special case. There is an example of this for an auto complete field. But how do I target the actual input field of an image field?
    – Joost
    Commented Sep 9, 2021 at 4:42
  • Can you add you form structure here (code) so that we can able to help you.
    – Ajay Reddy
    Commented Sep 13, 2021 at 4:49
  • It's no more than a regular checkbox and a regular image field from Drupal core, added to a content type. What code part do you wish to see, the html?
    – Joost
    Commented Sep 13, 2021 at 7:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.