acquia_vwo-1.0.x-dev/src/Form/ExtractIDForm.php
src/Form/ExtractIDForm.php
<?php namespace Drupal\acquia_vwo\Form; use Drupal\Core\Form\ConfigFormBase; use Drupal\Core\Form\FormStateInterface; /** * Defines the Extract ID Form. */ class ExtractIDForm extends ConfigFormBase { /** * {@inheritdoc} */ public function getFormId() { return 'acquia_vwo_settings_vwoid'; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $form = parent::buildForm($form, $form_state); $h[] = $this->t('Your VWO Account ID can be extracted from the "VWO Smart Code" available from the VWO site.'); $hl[] = $this->t('Log into your VWO account.'); $hl[] = $this->t('Locate the <em><strong>Settings</strong></em> menu down the left side of the site.'); $hl[] = $this->t('Click on <em><strong>Smart Code</strong></em> located along the top tabs.'); $hl[] = $this->t('Copy and paste the <em><strong>VWO Smart Code</strong></em> contents into the text box below.'); $h[] = $this->t('This can be found by following these simple directions:') . '<ul><li>' . implode('</li><li>', $hl) . '</li></ul>'; $form['help'] = [ '#markup' => '<p>' . implode('</p><p>', $h) . '</p>', ]; $form['current_id'] = [ '#type' => 'textfield', '#title' => $this->t('Current Account ID'), '#disabled' => TRUE, '#config_target' => 'acquia_vwo.settings:id', '#size' => 15, ]; $form['parse_area'] = [ '#type' => 'textarea', '#title' => $this->t('VWO Smart Code'), '#description' => $this->t('Paste the full VWO Smart Code and submit the form to extract the ID.'), '#rows' => '15', ]; $form['actions'] = [ '#type' => 'actions', 'extract' => [ '#type' => 'submit', '#value' => $this->t('Extract Account ID from pasted VWO Smart Code'), '#button_type' => 'primary', ], ]; return $form; } /** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { $pasted_code = $form_state->getValue('parse_area'); // Synchronous version of code. if (preg_match('/var\s*_vis_opt_account_id\s*=\s*(\d+);/', $pasted_code, $matches)) { $form_state->set('parsed_id', $matches[1]); } // Asynchronous version of code. elseif (preg_match('/var\s*account_id\s*=\s*(\d+);/', $pasted_code, $matches)) { $form_state->set('parsed_id', $matches[1]); } // Failure. else { $form_state->setErrorByName( 'parse_area', $this->t('Unable to locate Account ID in pasted code.') ); } } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { // Grab the editable configuration. $config = $this->config('acquia_vwo.settings'); // Set the parsed value. $config->set('id', $form_state->get('parsed_id')); // Commit saved configuration. $config->save(); // Redirect back to main settings page. $form_state->setRedirect('acquia_vwo.settings'); $this->messenger() ->addStatus($this->t('Saved Account ID as @id', ['@id' => $form_state->get('parsed_id')])); } /** * {@inheritdoc} */ protected function getEditableConfigNames() { return [ 'acquia_vwo.settings', ]; } }