Score:-2

Change required state by checking checkbox

jp flag

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?

leymannx avatar
ne flag
Does this answer your question: [How can I make a form element required with states?](https://drupal.stackexchange.com/q/14173/15055)
Joost avatar
jp flag
So using #states to make a field required is not possible. I should figure out a way to create my own validation. Thanks
leymannx avatar
ne flag
`#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.
Joost avatar
jp flag
@leymannx JS validation is fine for the use case I'm working on. But how can I make this work for an image field?
Score:1
ge flag

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'),
  ),
),
Joost avatar
jp flag
Thanks this already helped out a lot. I have one question though. At [this](https://www.drupal.org/docs/drupal-apis/form-api/conditional-form-fields#staterequired) 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?
Ajay Reddy avatar
ge flag
Can you add you form structure here (code) so that we can able to help you.
Joost avatar
jp flag
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?
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.