You are here

public function AbjsConditionForm::buildForm in A/B Test JS 8

Same name and namespace in other branches
  1. 2.0.x src/Form/AbjsConditionForm.php \Drupal\abjs\Form\AbjsConditionForm::buildForm()

Building the form.

Parameters

array $form: The form.

\Drupal\Core\Form\FormStateInterface $form_state: The state of forms.

int $cid: The ID of the item.

Overrides FormInterface::buildForm

File

src/Form/AbjsConditionForm.php, line 75

Class

AbjsConditionForm
Class for build form condition.

Namespace

Drupal\abjs\Form

Code

public function buildForm(array $form, FormStateInterface $form_state, $cid = NULL) {
  $form = [];
  $condition_name_default = "";
  $condition_script_default = "";
  if (!empty($cid)) {
    $condition_result = $this->database
      ->query('SELECT name, script FROM {abjs_condition} WHERE cid = :cid', [
      ':cid' => $cid,
    ]);
    $condition = $condition_result
      ->fetchObject();
    if (empty($condition)) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('The requested condition does not exist.'), 'error');
      return $form;
    }
    $condition_name_default = $condition->name;
    $condition_script_default = $condition->script;
    $form['cid'] = [
      '#type' => 'value',
      '#value' => $cid,
    ];
  }
  $form['name'] = [
    '#type' => 'textfield',
    '#title' => $this
      ->t('Condition Name'),
    '#default_value' => $condition_name_default,
    '#size' => 30,
    '#maxlength' => 50,
    '#required' => TRUE,
  ];
  $form['script'] = [
    '#type' => 'textarea',
    '#title' => $this
      ->t('Condition Script'),
    '#default_value' => $condition_script_default,
    '#description' => $this
      ->t('Any valid javascript with a return statement at the end, returning true or false. Read the documentation for examples'),
    '#rows' => 3,
    '#required' => TRUE,
  ];
  $form['actions'] = [
    '#type' => 'actions',
  ];
  $form['actions']['save'] = [
    '#type' => 'submit',
    '#value' => $this
      ->t('Save'),
    '#weight' => 5,
    '#submit' => [
      '::saveCondition',
    ],
    '#attributes' => [
      'class' => [
        "button button-action button--primary",
      ],
    ],
  ];
  $form['actions']['cancel'] = [
    '#type' => 'submit',
    '#value' => $this
      ->t('Cancel'),
    '#weight' => 10,
    '#submit' => [
      '::cancelCondition',
    ],
    '#limit_validation_errors' => [],
  ];
  if (!empty($cid)) {
    $form['actions']['delete'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Delete'),
      '#weight' => 15,
      '#submit' => [
        '::deleteCondition',
      ],
    ];
  }

  // Add ace code editor for syntax highlighting on the script field.
  if ($this
    ->configFactory()
    ->get('abjs.settings')
    ->get('ace') == 1) {
    $form['#attached']['library'][] = 'abjs/ace-editor';
  }
  return $form;
}