You are here

function business_rules_form_alter in Business Rules 8

Same name and namespace in other branches
  1. 2.x business_rules.module \business_rules_form_alter()

Implements hook_form_alter().

File

./business_rules.module, line 145
Business Rules module.

Code

function business_rules_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (method_exists($form_state
    ->getFormObject(), 'getEntity') && !$form_state
    ->isCached() && (!isset($_GET['ajax_form']) || $_GET['ajax_form'] != 1) && (!isset($_GET['_wrapper_format']) || $_GET['_wrapper_format'] != 'drupal_ajax')) {
    $entity = $form_state
      ->getFormObject()
      ->getEntity();
    if (\Drupal::service('business_rules.processor')
      ->ruleExists('form_validation', $entity)) {

      // Prepare the event for formValidation.
      $form_validation_reacts_on_definition = \Drupal::getContainer()
        ->get('plugin.manager.business_rules.reacts_on')
        ->getDefinition('form_validation');
      $form_validation_event = new BusinessRulesEvent($entity, [
        'form_id' => $form_id,
        'form_state' => $form_state,
        'form' => $form,
        'entity_type_id' => $entity
          ->getEntityTypeId(),
        'bundle' => $entity
          ->bundle(),
        'entity' => $entity,
        'entity_unchanged' => $entity->original,
        'reacts_on' => $form_validation_reacts_on_definition,
        'loop_control' => $entity
          ->getEntityTypeId() . $entity
          ->id(),
      ]);
      $form_state
        ->set('business_rules_event', $form_validation_event);

      // We can't dispatch this event here, otherwise it would be processed
      // before the form validation. In this case, the FormValidator will take
      // care of the event process and we are just adding this validation.
      $form['#validate'][] = 'Drupal\\business_rules\\Plugin\\BusinessRulesReactsOn\\FormValidation::validateForm';
    }
  }
}