Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DanLaufer/2f613591afc330a0e25ad8844d663c62 to your computer and use it in GitHub Desktop.
Save DanLaufer/2f613591afc330a0e25ad8844d663c62 to your computer and use it in GitHub Desktop.
Drupal 8 - Validate a minimum number of paragraphs
/**
* implements hook_form_node_form_alter()
* @author Daniel Laufer
* Add validation to the Resource Center content types.
*/
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
$node = $form_state->getFormObject()->getEntity();
$form['#validate'][] = '_mymodule_node_form_validate';
}
/**
* Validation function for all content types
*
* @return void
*/
function _mymodule_node_form_validate(&$form, FormStateInterface $form_state) {
// throw an error if we have less than 2 paragraph entities
$under_content_paragraphs = $form_state->getValue('field_under_content_sections');
if (!empty($under_content_paragraphs)) {
$count_of_related_resources = 0;
foreach($under_content_paragraphs as $parag) {
if(isset($parag['subform']['field_related_resources'])) {
$related_resource_field = $parag['subform']['field_related_resources'];
foreach($related_resource_field as $item) {
if(gettype($item) === 'array' && $item['target_id'] !== NULL) {
++$count_of_related_resources;
}
}
}
}
if($count_of_related_resources === 1) {
$form_state->setError($form['field_under_content_sections'], 'You cannot select only 1 related resources in the Under Content Section. Please select 2 or more, or select 0 and have it auto-populate.');
}
}
}
@Narkunan
Copy link

is there any other way of doing the validation without using form alter hook?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment