Last active
March 25, 2025 06:27
-
-
Save DanLaufer/2f613591afc330a0e25ad8844d663c62 to your computer and use it in GitHub Desktop.
Drupal 8 - Validate a minimum number of paragraphs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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.'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is there any other way of doing the validation without using form alter hook?