Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DanLaufer/88dd75fd05b24a30643dc2fbfa5b8dee to your computer and use it in GitHub Desktop.
Save DanLaufer/88dd75fd05b24a30643dc2fbfa5b8dee to your computer and use it in GitHub Desktop.
Drupal 8 - Custom validation on entity creation
//prevent 2 or more of the CTA paragraphs from being chosen in a paragraph reference field
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
$node = $form_state->getFormObject()->getEntity();
// Add validation to nodes by type
if(in_array($node->getType(),['campaign_page','case_study','event','insight','resource'])) {
$form['#validate'][] = '_mymodule_node_form_validate';
}
}
function _mymodule_node_form_validate(&$form, FormStateInterface $form_state) {
// Validates that we don't have two CTAs chosen in paragraph reference
$under_content_paragraphs = $form_state->getValue('field_under_content_sections');
if (!empty($form_state->getValue('field_under_content_sections'))) {
if(count($under_content_paragraphs) == 2) {
$keys_of_paragraphs = array_keys($under_content_paragraphs);
$has_one_cta_form = isset($under_content_paragraphs[$keys_of_paragraphs[0]]['subform']['field_cta'])
|| isset($under_content_paragraphs[$keys_of_paragraphs[0]]['subform']['field_half_width_ctas']);
$has_other_cta_form = isset($under_content_paragraphs[$keys_of_paragraphs[1]]['subform']['field_cta'])
|| isset($under_content_paragraphs[$keys_of_paragraphs[1]]['subform']['field_half_width_ctas']);
if($has_one_cta_form && $has_other_cta_form) {
$form_state->setError($form['field_under_content_sections'], 'Cannot have two CTA paragraphs selected in the Under Content Section.');
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment