Example #1
0
 /**
  * Loops through and displays all form errors.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 protected function displayErrorMessages(array $form, FormStateInterface $form_state)
 {
     $error_links = [];
     $errors = $form_state->getErrors();
     // Loop through all form errors and check if we need to display a link.
     foreach ($errors as $name => $error) {
         $form_element = FormElementHelper::getElementByName($name, $form);
         $title = FormElementHelper::getElementTitle($form_element);
         // Only show links to erroneous elements that are visible.
         $is_visible_element = Element::isVisibleElement($form_element);
         // Only show links for elements that have a title themselves or have
         // children with a title.
         $has_title = !empty($title);
         // Only show links for elements with an ID.
         $has_id = !empty($form_element['#id']);
         // Do not show links to elements with suppressed messages. Most often
         // their parent element is used for inline errors.
         if (!empty($form_element['#error_no_message'])) {
             unset($errors[$name]);
         } elseif ($is_visible_element && $has_title && $has_id) {
             // We need to pass this through SafeMarkup::escape() so
             // drupal_set_message() does not encode the links.
             $error_links[] = SafeMarkup::escape($this->l($title, Url::fromRoute('<none>', [], ['fragment' => $form_element['#id'], 'external' => TRUE])));
             unset($errors[$name]);
         }
     }
     // Set normal error messages for all remaining errors.
     foreach ($errors as $error) {
         $this->drupalSetMessage($error, 'error');
     }
     if (!empty($error_links)) {
         $message = $this->formatPlural(count($error_links), '1 error has been found: !errors', '@count errors have been found: !errors', ['!errors' => SafeMarkup::set(implode(', ', $error_links))]);
         $this->drupalSetMessage($message, 'error');
     }
 }
Example #2
0
 /**
  * Loops through and displays all form errors.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 protected function displayErrorMessages(array $form, FormStateInterface $form_state)
 {
     $error_links = [];
     $errors = $form_state->getErrors();
     // Loop through all form errors and check if we need to display a link.
     foreach ($errors as $name => $error) {
         $form_element = FormElementHelper::getElementByName($name, $form);
         $title = FormElementHelper::getElementTitle($form_element);
         // Only show links to erroneous elements that are visible.
         $is_visible_element = Element::isVisibleElement($form_element);
         // Only show links for elements that have a title themselves or have
         // children with a title.
         $has_title = !empty($title);
         // Only show links for elements with an ID.
         $has_id = !empty($form_element['#id']);
         // Do not show links to elements with suppressed messages. Most often
         // their parent element is used for inline errors.
         if (!empty($form_element['#error_no_message'])) {
             unset($errors[$name]);
         } elseif ($is_visible_element && $has_title && $has_id) {
             $error_links[] = $this->l($title, Url::fromRoute('<none>', [], ['fragment' => $form_element['#id'], 'external' => TRUE]));
             unset($errors[$name]);
         }
     }
     // Set normal error messages for all remaining errors.
     foreach ($errors as $error) {
         $this->drupalSetMessage($error, 'error');
     }
     if (!empty($error_links)) {
         $render_array = [['#markup' => $this->formatPlural(count($error_links), '1 error has been found: ', '@count errors have been found: ')], ['#theme' => 'item_list', '#items' => $error_links, '#context' => ['list_style' => 'comma-list']]];
         $message = $this->renderer->renderPlain($render_array);
         $this->drupalSetMessage($message, 'error');
     }
 }
Example #3
0
 /**
  * Loops through and displays all form errors.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 protected function displayErrorMessages(array $form, FormStateInterface $form_state)
 {
     $errors = $form_state->getErrors();
     // Loop through all form errors and set an error message.
     foreach ($errors as $error) {
         $this->drupalSetMessage($error, 'error');
     }
 }
 /**
  * Implements \Drupal\Core\Form\FormInterface::buildForm().
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $ups_config = $this->config('uc_ups.settings');
     // Put fieldsets into vertical tabs
     $form['ups-settings'] = array('#type' => 'vertical_tabs', '#attached' => array('library' => array('uc_ups/uc_ups.scripts')));
     // Container for credential forms
     $form['uc_ups_credentials'] = array('#type' => 'details', '#title' => $this->t('Credentials'), '#description' => $this->t('Account number and authorization information.'), '#group' => 'ups-settings');
     $form['uc_ups_credentials']['uc_ups_access_license'] = array('#type' => 'textfield', '#title' => $this->t('UPS OnLine Tools XML Access Key'), '#default_value' => $ups_config->get('access_license'), '#required' => TRUE);
     $form['uc_ups_credentials']['uc_ups_shipper_number'] = array('#type' => 'textfield', '#title' => $this->t('UPS Shipper #'), '#description' => $this->t('The 6-character string identifying your UPS account as a shipper.'), '#default_value' => $ups_config->get('shipper_number'), '#required' => TRUE);
     $form['uc_ups_credentials']['uc_ups_user_id'] = array('#type' => 'textfield', '#title' => $this->t('UPS.com user ID'), '#default_value' => $ups_config->get('user_id'), '#required' => TRUE);
     $form['uc_ups_credentials']['uc_ups_password'] = array('#type' => 'password', '#title' => $this->t('Password'), '#default_value' => $ups_config->get('password'));
     $form['uc_ups_credentials']['uc_ups_connection_address'] = array('#type' => 'select', '#title' => $this->t('Server mode'), '#description' => $this->t('Use the Testing server while developing and configuring your site. Switch to the Production server only after you have demonstrated that transactions on the Testing server are working and you are ready to go live.'), '#options' => array('https://wwwcie.ups.com/ups.app/xml/' => $this->t('Testing'), 'https://onlinetools.ups.com/ups.app/xml/' => $this->t('Production')), '#default_value' => $ups_config->get('connection_address'));
     $form['services'] = array('#type' => 'details', '#title' => $this->t('Service options'), '#description' => $this->t('Set the conditions that will return a UPS quote.'), '#group' => 'ups-settings');
     $form['services']['uc_ups_services'] = array('#type' => 'checkboxes', '#title' => $this->t('UPS services'), '#default_value' => $ups_config->get('services'), '#options' => UPSUtilities::services(), '#description' => $this->t('Select the UPS services that are available to customers.'));
     // Container for quote options
     $form['uc_ups_quote_options'] = array('#type' => 'details', '#title' => $this->t('Quote options'), '#description' => $this->t('Preferences that affect computation of quote.'), '#group' => 'ups-settings');
     $form['uc_ups_quote_options']['uc_ups_all_in_one'] = array('#type' => 'radios', '#title' => $this->t('Product packages'), '#default_value' => $ups_config->get('all_in_one'), '#options' => array(0 => $this->t('Each product in its own package'), 1 => $this->t('All products in one package')), '#description' => $this->t('Indicate whether each product is quoted as shipping separately or all in one package. Orders with one kind of product will still use the package quantity to determine the number of packages needed, however.'));
     // Form to select package types
     $form['uc_ups_quote_options']['uc_ups_package_type'] = array('#type' => 'select', '#title' => $this->t('Default Package Type'), '#default_value' => $ups_config->get('package_type'), '#options' => UPSUtilities::packageTypes(), '#description' => $this->t('Type of packaging to be used.  May be overridden on a per-product basis via the product node edit form.'));
     $form['uc_ups_quote_options']['uc_ups_classification'] = array('#type' => 'select', '#title' => $this->t('UPS Customer classification'), '#options' => array('01' => $this->t('Wholesale'), '03' => $this->t('Occasional'), '04' => $this->t('Retail')), '#default_value' => $ups_config->get('classification'), '#description' => $this->t('The kind of customer you are to UPS. For daily pickups the default is wholesale; for customer counter pickups the default is retail; for other pickups the default is occasional.'));
     $form['uc_ups_quote_options']['uc_ups_negotiated_rates'] = array('#type' => 'radios', '#title' => $this->t('Negotiated rates'), '#default_value' => $ups_config->get('negotiated_rates'), '#options' => array(1 => $this->t('Yes'), 0 => $this->t('No')), '#description' => $this->t('Is your UPS account receiving negotiated rates on shipments?'));
     // Form to select pickup type
     $form['uc_ups_quote_options']['uc_ups_pickup_type'] = array('#type' => 'select', '#title' => $this->t('Pickup type'), '#options' => array('01' => 'Daily Pickup', '03' => 'Customer Counter', '06' => 'One Time Pickup', '07' => 'On Call Air', '11' => 'Suggested Retail Rates', '19' => 'Letter Center', '20' => 'Air Service Center'), '#default_value' => $ups_config->get('pickup_type'));
     $form['uc_ups_quote_options']['uc_ups_residential_quotes'] = array('#type' => 'radios', '#title' => $this->t('Assume UPS shipping quotes will be delivered to'), '#default_value' => $ups_config->get('residential_quotes'), '#options' => array(0 => $this->t('Business locations'), 1 => $this->t('Residential locations (extra fees)')));
     $form['uc_ups_quote_options']['uc_ups_unit_system'] = array('#type' => 'select', '#title' => $this->t('System of measurement'), '#default_value' => $ups_config->get('unit_system', \Drupal::config('uc_store.settings')->get('length.units')), '#options' => array('in' => $this->t('Imperial'), 'cm' => $this->t('Metric')), '#description' => $this->t('Choose the standard system of measurement for your country.'));
     $form['uc_ups_quote_options']['uc_ups_insurance'] = array('#type' => 'checkbox', '#title' => $this->t('Package insurance'), '#default_value' => $ups_config->get('insurance'), '#description' => $this->t('When enabled, the quotes presented to the customer will include the cost of insurance for the full sales price of all products in the order.'));
     // Container for markup forms
     $form['uc_ups_markups'] = array('#type' => 'details', '#title' => $this->t('Markups'), '#description' => $this->t('Modifiers to the shipping weight and quoted rate.'), '#group' => 'ups-settings');
     // Form to select type of rate markup
     $form['uc_ups_markups']['uc_ups_rate_markup_type'] = array('#type' => 'select', '#title' => $this->t('Rate markup type'), '#default_value' => $ups_config->get('rate_markup_type'), '#options' => array('percentage' => $this->t('Percentage (%)'), 'multiplier' => $this->t('Multiplier (×)'), 'currency' => $this->t('Addition (@currency)', ['@currency' => \Drupal::config('uc_store.settings')->get('currency.symbol')])));
     // Form to select rate markup amount
     $form['uc_ups_markups']['uc_ups_rate_markup'] = array('#type' => 'textfield', '#title' => $this->t('Shipping rate markup'), '#default_value' => $ups_config->get('rate_markup'), '#description' => $this->t('Markup shipping rate quote by currency amount, percentage, or multiplier.'));
     // Form to select type of weight markup
     $form['uc_ups_markups']['uc_ups_weight_markup_type'] = array('#type' => 'select', '#title' => $this->t('Weight markup type'), '#default_value' => $ups_config->get('weight_markup_type'), '#options' => array('percentage' => $this->t('Percentage (%)'), 'multiplier' => $this->t('Multiplier (×)'), 'mass' => $this->t('Addition (@mass)', ['@mass' => '#'])), '#disabled' => TRUE);
     // Form to select weight markup amount
     $form['uc_ups_markups']['uc_ups_weight_markup'] = array('#type' => 'textfield', '#title' => $this->t('Shipping weight markup'), '#default_value' => $ups_config->get('weight_markup'), '#description' => $this->t('Markup UPS shipping weight on a per-package basis before quote, by weight amount, percentage, or multiplier.'), '#disabled' => TRUE);
     // Container for label printing
     $form['uc_ups_labels'] = array('#type' => 'details', '#title' => $this->t('Label Printing'), '#description' => $this->t('Preferences for UPS Shipping Label Printing.  Additional permissions from UPS are required to use this feature.'), '#group' => 'ups-settings');
     $intervals = array(86400, 302400, 604800, 1209600, 2419200, 0);
     $period = array_map(array(\Drupal::service('date.formatter'), 'formatInterval'), array_combine($intervals, $intervals));
     $period[0] = $this->t('Forever');
     // Form to select how long labels stay on server
     $form['uc_ups_labels']['uc_ups_label_lifetime'] = array('#type' => 'select', '#title' => $this->t('Label lifetime'), '#default_value' => $ups_config->get('label_lifetime'), '#options' => $period, '#description' => $this->t('Controls how long labels are stored on the server before being automatically deleted. Cron must be enabled for automatic deletion. Default is never delete the labels, keep them forever.'));
     // Taken from system_settings_form(). Only, don't use its submit handler.
     $form['actions']['#type'] = 'actions';
     $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Save configuration'));
     $form['actions']['cancel'] = array('#type' => 'link', '#title' => $this->t('Cancel'), '#url' => Url::fromRoute('entity.uc_quote_method.collection'));
     if (!empty($_POST) && $form_state->getErrors()) {
         drupal_set_message($this->t('The settings have not been saved because of the errors.'), 'error');
     }
     if (!isset($form['#theme'])) {
         $form['#theme'] = 'system_settings_form';
     }
     return parent::buildForm($form, $form_state);
 }
Example #5
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     if ($form_state->getErrors()) {
         unset($form['#prefix'], $form['#suffix']);
         $form['status_messages'] = ['#type' => 'status_messages', '#weight' => -10];
         $response->addCommand(new HtmlCommand('#editor-link-dialog-form', $form));
     } else {
         $response->addCommand(new EditorDialogSave($form_state->getValues()));
         $response->addCommand(new CloseModalDialogCommand());
     }
     return $response;
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     if ($form_state->getErrors()) {
         unset($form['#prefix'], $form['#suffix']);
         $status_messages = array('#theme' => 'status_messages');
         $output = drupal_render($form);
         $output = '<div>' . drupal_render($status_messages) . $output . '</div>';
         $response->addCommand(new HtmlCommand('#editor-link-dialog-form', $output));
     } else {
         $response->addCommand(new EditorDialogSave($form_state->getValues()));
         $response->addCommand(new CloseModalDialogCommand());
     }
     return $response;
 }
 /**
  * Implements \Drupal\Core\Form\FormInterface::buildForm().
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $usps_config = $this->config('uc_usps.settings');
     // Put fieldsets into vertical tabs
     $form['usps-settings'] = array('#type' => 'vertical_tabs', '#attached' => array('library' => array('uc_usps/uc_usps.scripts')));
     // Container for credential forms
     $form['uc_usps_credentials'] = array('#type' => 'details', '#title' => $this->t('Credentials'), '#description' => $this->t('Account number and authorization information.'), '#group' => 'usps-settings');
     $form['uc_usps_credentials']['uc_usps_user_id'] = array('#type' => 'textfield', '#title' => $this->t('USPS user ID'), '#description' => $this->t('To acquire or locate your user ID, refer to the <a href=":url">USPS documentation</a>.', [':url' => 'http://drupal.org/node/1308256']), '#default_value' => $usps_config->get('user_id'));
     $form['domestic'] = array('#type' => 'details', '#title' => $this->t('USPS Domestic'), '#description' => $this->t('Set the conditions that will return a USPS quote.'), '#group' => 'usps-settings');
     $form['domestic']['uc_usps_online_rates'] = array('#type' => 'checkbox', '#title' => $this->t('Display USPS "online" rates'), '#default_value' => $usps_config->get('online_rates'), '#description' => $this->t('Show your customer standard USPS rates (default) or discounted "online" rates.  Online rates apply only if you, the merchant, pay for and print out postage from the USPS <a href="https://cns.usps.com/labelInformation.shtml">Click-N-Ship</a> web site.'));
     $form['domestic']['uc_usps_env_services'] = array('#type' => 'checkboxes', '#title' => $this->t('USPS envelope services'), '#default_value' => $usps_config->get('env_services'), '#options' => \Drupal\uc_usps\USPSUtilities::envelopeServices(), '#description' => $this->t('Select the USPS services that are available to customers. Be sure to include the services that the Postal Service agrees are available to you.'));
     $form['domestic']['uc_usps_services'] = array('#type' => 'checkboxes', '#title' => $this->t('USPS parcel services'), '#default_value' => $usps_config->get('services'), '#options' => \Drupal\uc_usps\USPSUtilities::services(), '#description' => $this->t('Select the USPS services that are available to customers. Be sure to include the services that the Postal Service agrees are available to you.'));
     $form['international'] = array('#type' => 'details', '#title' => $this->t('USPS International'), '#description' => $this->t('Set the conditions that will return a USPS International quote.'), '#group' => 'usps-settings');
     $form['international']['uc_usps_intl_env_services'] = array('#type' => 'checkboxes', '#title' => $this->t('USPS international envelope services'), '#default_value' => $usps_config->get('intl_env_services'), '#options' => \Drupal\uc_usps\USPSUtilities::internationalEnvelopeServices(), '#description' => $this->t('Select the USPS services that are available to customers. Be sure to include the services that the Postal Service agrees are available to you.'));
     $form['international']['uc_usps_intl_services'] = array('#type' => 'checkboxes', '#title' => $this->t('USPS international parcel services'), '#default_value' => $usps_config->get('intl_services'), '#options' => \Drupal\uc_usps\USPSUtilities::internationalServices(), '#description' => $this->t('Select the USPS services that are available to customers. Be sure to include the services that the Postal Service agrees are available to you.'));
     // Container for quote options
     $form['uc_usps_quote_options'] = array('#type' => 'details', '#title' => $this->t('Quote options'), '#description' => $this->t('Preferences that affect computation of quote.'), '#group' => 'usps-settings');
     $form['uc_usps_quote_options']['uc_usps_all_in_one'] = array('#type' => 'radios', '#title' => $this->t('Product packages'), '#default_value' => $usps_config->get('all_in_one'), '#options' => array(0 => $this->t('Each product in its own package'), 1 => $this->t('All products in one package')), '#description' => $this->t('Indicate whether each product is quoted as shipping separately or all in one package. Orders with one kind of product will still use the package quantity to determine the number of packages needed, however.'));
     // Insurance
     $form['uc_usps_quote_options']['uc_usps_insurance'] = array('#type' => 'checkbox', '#title' => $this->t('Package insurance'), '#default_value' => $usps_config->get('insurance'), '#description' => $this->t('When enabled, the quotes presented to the customer will include the cost of insurance for the full sales price of all products in the order.'), '#disabled' => TRUE);
     // Delivery Confirmation
     $form['uc_usps_quote_options']['uc_usps_delivery_confirmation'] = array('#type' => 'checkbox', '#title' => $this->t('Delivery confirmation'), '#default_value' => $usps_config->get('delivery_confirmation'), '#description' => $this->t('When enabled, the quotes presented to the customer will include the cost of delivery confirmation for all packages in the order.'), '#disabled' => TRUE);
     // Signature Confirmation
     $form['uc_usps_quote_options']['uc_usps_signature_confirmation'] = array('#type' => 'checkbox', '#title' => $this->t('Signature confirmation'), '#default_value' => $usps_config->get('signature_confirmation'), '#description' => $this->t('When enabled, the quotes presented to the customer will include the cost of signature confirmation for all packages in the order.'), '#disabled' => TRUE);
     // Container for markup forms
     $form['uc_usps_markups'] = array('#type' => 'details', '#title' => $this->t('Markups'), '#description' => $this->t('Modifiers to the shipping weight and quoted rate.'), '#group' => 'usps-settings');
     $form['uc_usps_markups']['uc_usps_rate_markup_type'] = array('#type' => 'select', '#title' => $this->t('Rate markup type'), '#default_value' => $usps_config->get('rate_markup_type'), '#options' => array('percentage' => $this->t('Percentage (%)'), 'multiplier' => $this->t('Multiplier (×)'), 'currency' => $this->t('Addition (!currency)', array('!currency' => \Drupal::config('uc_store.settings')->get('currency.symbol')))));
     $form['uc_usps_markups']['uc_usps_rate_markup'] = array('#type' => 'textfield', '#title' => $this->t('Shipping rate markup'), '#default_value' => $usps_config->get('rate_markup'), '#description' => $this->t('Markup shipping rate quote by dollar amount, percentage, or multiplier.'));
     // Form to select type of weight markup
     $form['uc_usps_markups']['uc_usps_weight_markup_type'] = array('#type' => 'select', '#title' => $this->t('Weight markup type'), '#default_value' => $usps_config->get('weight_markup_type'), '#options' => array('percentage' => $this->t('Percentage (%)'), 'multiplier' => $this->t('Multiplier (×)'), 'mass' => $this->t('Addition (!mass)', array('!mass' => '#'))), '#disabled' => TRUE);
     // Form to select weight markup amount
     $form['uc_usps_markups']['uc_usps_weight_markup'] = array('#type' => 'textfield', '#title' => $this->t('Shipping weight markup'), '#default_value' => 0, '#description' => $this->t('Markup shipping weight on a per-package basis before quote, by weight amount, percentage, or multiplier.'), '#disabled' => TRUE);
     // Taken from system_settings_form(). Only, don't use its submit handler.
     $form['actions']['#type'] = 'actions';
     $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Save configuration'));
     $form['actions']['cancel'] = array('#markup' => $this->l($this->t('Cancel'), new Url('uc_quote.methods')));
     if (!empty($_POST) && $form_state->getErrors()) {
         drupal_set_message($this->t('The settings have not been saved because of the errors.'), 'error');
     }
     if (!isset($form['#theme'])) {
         $form['#theme'] = 'system_settings_form';
     }
     return parent::buildForm($form, $form_state);
 }
Example #8
0
 /**
  * Implements the sumbit handler for the ajax call.
  *
  * @param array $form
  *   Render array representing from.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   Current form state.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  *   Array of ajax commands to execute on submit of the modal form.
  */
 public function ajaxSubmitForm(array &$form, FormStateInterface $form_state)
 {
     // At this point the submit handler has fired.
     // Clear the message set by the submit handler.
     drupal_get_messages();
     // We begin building a new ajax reponse.
     $response = new AjaxResponse();
     if ($form_state->getErrors()) {
         unset($form['#prefix']);
         unset($form['#suffix']);
         $form['status_messages'] = ['#type' => 'status_messages', '#weight' => -10];
         $response->addCommand(new HtmlCommand('#fapi-example-modal-form', $form));
     } else {
         $title = $form_state->getValue('title');
         $message = t('You specified a title of %title.', ['%title' => $title]);
         $content = ['#type' => 'html_tag', '#tag' => 'p', '#value' => $message];
         $response->addCommand(new HtmlCommand('#fapi-example-message', $content));
         $response->addCommand(new CloseModalDialogCommand());
     }
     return $response;
 }
Example #9
0
 /**
  * {@inheritdoc}
  *
  * Most block plugins should not override this method. To add submission
  * handling for a specific block type, override BlockBase::blockSubmit().
  *
  * @see \Drupal\Core\Block\BlockBase::blockSubmit()
  */
 public function submitConfigurationForm(array &$form, FormStateInterface $form_state)
 {
     // Process the block's submission handling if no errors occurred only.
     if (!$form_state->getErrors()) {
         $this->configuration['label'] = $form_state->getValue('label');
         $this->configuration['label_display'] = $form_state->getValue('label_display');
         $this->configuration['provider'] = $form_state->getValue('provider');
         $this->blockSubmit($form, $form_state);
     }
 }
Example #10
0
 /**
  * {@inheritdoc}
  */
 public function getErrors()
 {
     return $this->mainFormState->getErrors();
 }
 /**
  * @covers ::getErrors
  */
 public function testGetErrors()
 {
     $errors = ['foo' => 'bar'];
     $this->decoratedFormState->getErrors()->willReturn($errors)->shouldBeCalled();
     $this->assertSame($errors, $this->formStateDecoratorBase->getErrors());
 }
 /**
  * {@inheritdoc}
  */
 public function getErrors()
 {
     return $this->decoratedFormState->getErrors();
 }
Example #13
0
 /**
  * {@inheritdoc}
  */
 public function selectItemAjax(array &$form, FormStateInterface $form_state)
 {
     $errors = $form_state->getErrors();
     if ($errors) {
         return self::ajaxRenderFormAndMessages($form);
     }
     $response = new AjaxResponse();
     // Hidden input value set by javascript.
     $values = $form_state->getValues();
     $values['entity_id'] = $form_state->getUserInput()['result_chosen'];
     $response->addCommand(new EmbridgeSearchSave($values));
     $response->addCommand(new CloseModalDialogCommand());
     return $response;
 }
Example #14
0
 /**
  * Form constructor.
  *
  * Display a tree of all the terms in a vocabulary, with options to edit
  * each one. The form is made drag and drop by the theme function.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  * @param \Drupal\taxonomy\VocabularyInterface $taxonomy_vocabulary
  *   The vocabulary to display the overview form for.
  *
  * @return array
  *   The form structure.
  */
 public function buildForm(array $form, FormStateInterface $form_state, VocabularyInterface $taxonomy_vocabulary = NULL)
 {
     // @todo Remove global variables when https://www.drupal.org/node/2044435 is
     //   in.
     global $pager_page_array, $pager_total, $pager_total_items;
     $form_state->set(['taxonomy', 'vocabulary'], $taxonomy_vocabulary);
     $parent_fields = FALSE;
     $page = $this->getRequest()->query->get('page') ?: 0;
     // Number of terms per page.
     $page_increment = $this->config('taxonomy.settings')->get('terms_per_page_admin');
     // Elements shown on this page.
     $page_entries = 0;
     // Elements at the root level before this page.
     $before_entries = 0;
     // Elements at the root level after this page.
     $after_entries = 0;
     // Elements at the root level on this page.
     $root_entries = 0;
     // Terms from previous and next pages are shown if the term tree would have
     // been cut in the middle. Keep track of how many extra terms we show on
     // each page of terms.
     $back_step = NULL;
     $forward_step = 0;
     // An array of the terms to be displayed on this page.
     $current_page = array();
     $delta = 0;
     $term_deltas = array();
     $tree = $this->storageController->loadTree($taxonomy_vocabulary->id(), 0, NULL, TRUE);
     $tree_index = 0;
     do {
         // In case this tree is completely empty.
         if (empty($tree[$tree_index])) {
             break;
         }
         $delta++;
         // Count entries before the current page.
         if ($page && $page * $page_increment > $before_entries && !isset($back_step)) {
             $before_entries++;
             continue;
         } elseif ($page_entries > $page_increment && isset($complete_tree)) {
             $after_entries++;
             continue;
         }
         // Do not let a term start the page that is not at the root.
         $term = $tree[$tree_index];
         if (isset($term->depth) && $term->depth > 0 && !isset($back_step)) {
             $back_step = 0;
             while ($pterm = $tree[--$tree_index]) {
                 $before_entries--;
                 $back_step++;
                 if ($pterm->depth == 0) {
                     $tree_index--;
                     // Jump back to the start of the root level parent.
                     continue 2;
                 }
             }
         }
         $back_step = isset($back_step) ? $back_step : 0;
         // Continue rendering the tree until we reach the a new root item.
         if ($page_entries >= $page_increment + $back_step + 1 && $term->depth == 0 && $root_entries > 1) {
             $complete_tree = TRUE;
             // This new item at the root level is the first item on the next page.
             $after_entries++;
             continue;
         }
         if ($page_entries >= $page_increment + $back_step) {
             $forward_step++;
         }
         // Finally, if we've gotten down this far, we're rendering a term on this
         // page.
         $page_entries++;
         $term_deltas[$term->id()] = isset($term_deltas[$term->id()]) ? $term_deltas[$term->id()] + 1 : 0;
         $key = 'tid:' . $term->id() . ':' . $term_deltas[$term->id()];
         // Keep track of the first term displayed on this page.
         if ($page_entries == 1) {
             $form['#first_tid'] = $term->id();
         }
         // Keep a variable to make sure at least 2 root elements are displayed.
         if ($term->parents[0] == 0) {
             $root_entries++;
         }
         $current_page[$key] = $term;
     } while (isset($tree[++$tree_index]));
     // Because we didn't use a pager query, set the necessary pager variables.
     $total_entries = $before_entries + $page_entries + $after_entries;
     $pager_total_items[0] = $total_entries;
     $pager_page_array[0] = $page;
     $pager_total[0] = ceil($total_entries / $page_increment);
     // If this form was already submitted once, it's probably hit a validation
     // error. Ensure the form is rebuilt in the same order as the user
     // submitted.
     $user_input = $form_state->getUserInput();
     if (!empty($user_input)) {
         // Get the POST order.
         $order = array_flip(array_keys($user_input['terms']));
         // Update our form with the new order.
         $current_page = array_merge($order, $current_page);
         foreach ($current_page as $key => $term) {
             // Verify this is a term for the current page and set at the current
             // depth.
             if (is_array($user_input['terms'][$key]) && is_numeric($user_input['terms'][$key]['term']['tid'])) {
                 $current_page[$key]->depth = $user_input['terms'][$key]['term']['depth'];
             } else {
                 unset($current_page[$key]);
             }
         }
     }
     $errors = $form_state->getErrors();
     $destination = $this->getDestinationArray();
     $row_position = 0;
     // Build the actual form.
     $form['terms'] = array('#type' => 'table', '#header' => array($this->t('Name'), $this->t('Weight'), $this->t('Operations')), '#empty' => $this->t('No terms available. <a href=":link">Add term</a>.', array(':link' => $this->url('entity.taxonomy_term.add_form', array('taxonomy_vocabulary' => $taxonomy_vocabulary->id())))), '#attributes' => array('id' => 'taxonomy'));
     foreach ($current_page as $key => $term) {
         /** @var $term \Drupal\Core\Entity\EntityInterface */
         $form['terms'][$key]['#term'] = $term;
         $indentation = array();
         if (isset($term->depth) && $term->depth > 0) {
             $indentation = array('#theme' => 'indentation', '#size' => $term->depth);
         }
         $form['terms'][$key]['term'] = array('#prefix' => !empty($indentation) ? drupal_render($indentation) : '', '#type' => 'link', '#title' => $term->getName(), '#url' => $term->urlInfo());
         if ($taxonomy_vocabulary->getHierarchy() != TAXONOMY_HIERARCHY_MULTIPLE && count($tree) > 1) {
             $parent_fields = TRUE;
             $form['terms'][$key]['term']['tid'] = array('#type' => 'hidden', '#value' => $term->id(), '#attributes' => array('class' => array('term-id')));
             $form['terms'][$key]['term']['parent'] = array('#type' => 'hidden', '#default_value' => $term->parents[0], '#attributes' => array('class' => array('term-parent')));
             $form['terms'][$key]['term']['depth'] = array('#type' => 'hidden', '#default_value' => $term->depth, '#attributes' => array('class' => array('term-depth')));
         }
         $form['terms'][$key]['weight'] = array('#type' => 'weight', '#delta' => $delta, '#title' => $this->t('Weight for added term'), '#title_display' => 'invisible', '#default_value' => $term->getWeight(), '#attributes' => array('class' => array('term-weight')));
         $operations = array('edit' => array('title' => $this->t('Edit'), 'query' => $destination, 'url' => $term->urlInfo('edit-form')), 'delete' => array('title' => $this->t('Delete'), 'query' => $destination, 'url' => $term->urlInfo('delete-form')));
         if ($this->moduleHandler->moduleExists('content_translation') && content_translation_translate_access($term)->isAllowed()) {
             $operations['translate'] = array('title' => $this->t('Translate'), 'query' => $destination, 'url' => $term->urlInfo('drupal:content-translation-overview'));
         }
         $form['terms'][$key]['operations'] = array('#type' => 'operations', '#links' => $operations);
         $form['terms'][$key]['#attributes']['class'] = array();
         if ($parent_fields) {
             $form['terms'][$key]['#attributes']['class'][] = 'draggable';
         }
         // Add classes that mark which terms belong to previous and next pages.
         if ($row_position < $back_step || $row_position >= $page_entries - $forward_step) {
             $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-preview';
         }
         if ($row_position !== 0 && $row_position !== count($tree) - 1) {
             if ($row_position == $back_step - 1 || $row_position == $page_entries - $forward_step - 1) {
                 $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-top';
             } elseif ($row_position == $back_step || $row_position == $page_entries - $forward_step) {
                 $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-bottom';
             }
         }
         // Add an error class if this row contains a form error.
         foreach ($errors as $error_key => $error) {
             if (strpos($error_key, $key) === 0) {
                 $form['terms'][$key]['#attributes']['class'][] = 'error';
             }
         }
         $row_position++;
     }
     if ($parent_fields) {
         $form['terms']['#tabledrag'][] = array('action' => 'match', 'relationship' => 'parent', 'group' => 'term-parent', 'subgroup' => 'term-parent', 'source' => 'term-id', 'hidden' => FALSE);
         $form['terms']['#tabledrag'][] = array('action' => 'depth', 'relationship' => 'group', 'group' => 'term-depth', 'hidden' => FALSE);
         $form['terms']['#attached']['library'][] = 'taxonomy/drupal.taxonomy';
         $form['terms']['#attached']['drupalSettings']['taxonomy'] = ['backStep' => $back_step, 'forwardStep' => $forward_step];
     }
     $form['terms']['#tabledrag'][] = array('action' => 'order', 'relationship' => 'sibling', 'group' => 'term-weight');
     if ($taxonomy_vocabulary->getHierarchy() != TAXONOMY_HIERARCHY_MULTIPLE && count($tree) > 1) {
         $form['actions'] = array('#type' => 'actions', '#tree' => FALSE);
         $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Save'), '#button_type' => 'primary');
         $form['actions']['reset_alphabetical'] = array('#type' => 'submit', '#submit' => array('::submitReset'), '#value' => $this->t('Reset to alphabetical'));
     }
     $form['pager_pager'] = ['#type' => 'pager'];
     return $form;
 }
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function massageFormValues(array $values, array $form, FormStateInterface $form_state)
 {
     // Don't do entity saving when we have validation erors.
     if (count($form_state->getErrors()) || !$form_state->isValidationComplete()) {
         return $values;
     }
     $field_name = $this->fieldDefinition->getName();
     $widget_state = static::getWidgetState($form['#parents'], $field_name, $form_state);
     $element = NestedArray::getValue($form_state->getCompleteForm(), $widget_state['array_parents']);
     foreach ($values as $delta => &$item) {
         if (isset($widget_state['paragraphs'][$item['_original_delta']]['entity']) && $widget_state['paragraphs'][$item['_original_delta']]['mode'] != 'remove') {
             $paragraphs_entity = $widget_state['paragraphs'][$item['_original_delta']]['entity'];
             /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $display */
             $display = $widget_state['paragraphs'][$item['_original_delta']]['display'];
             $display->extractFormValues($paragraphs_entity, $element[$item['_original_delta']]['subform'], $form_state);
             $display->validateFormValues($paragraphs_entity, $element[$item['_original_delta']]['subform'], $form_state);
             $paragraphs_entity->setNewRevision(TRUE);
             $paragraphs_entity->save();
             $item['target_id'] = $paragraphs_entity->id();
             $item['target_revision_id'] = $paragraphs_entity->getRevisionId();
         } elseif ($widget_state['paragraphs'][$item['_original_delta']]['mode'] == 'remove' || $widget_state['paragraphs'][$item['_original_delta']]['mode'] == 'removed') {
             $item['target_id'] = NULL;
             $item['target_revision_id'] = NULL;
         }
     }
     return $values;
 }
Example #16
0
 /**
  * {@inheritdoc}
  */
 public function submitConfigurationForm(array &$form, FormStateInterface $formState)
 {
     if (!$formState->getErrors()) {
         $this->configuration['name'] = $formState->getValue('name');
     }
 }
 /**
  * An AJAX submit callback to validate the WYSIWYG modal.
  */
 public function ajaxSubmit(array &$form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     if (!$form_state->getErrors()) {
         // Load the provider and get the information needed for the client.
         $provider = $this->getProvider($form_state->getValue('video_url'));
         $response->addCommand(new EditorDialogSave($this->getClientValues($form_state, $provider)));
         $response->addCommand(new CloseModalDialogCommand());
     } else {
         unset($form['#prefix'], $form['#suffix']);
         $form['status_messages'] = ['#type' => 'status_messages', '#weight' => -10];
         $response->addCommand(new HtmlCommand(NULL, $form));
     }
     return $response;
 }
 /**
  * Ajax callback for save button.
  *
  * Sets attributes for the image and return an ajax response in order to
  * save the data into the editor.
  *
  * @param array $form
  *   The form array.
  * @param FormStateInterface $form_state
  *   The form state object.
  *
  * @return AjaxResponse
  *   An ajax response to add the image to the editor.
  */
 public function ajaxSave(array &$form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     // Convert any uploaded files from the FID values to data-entity-uuid
     // attributes and set data-entity-type to 'file'.
     $asset_id = $form_state->getValue(array('asset', 0));
     if (!empty($asset_id)) {
         /** @var \Drupal\embridge\EmbridgeAssetEntityInterface $asset */
         $asset = $this->entityTypeManager->getStorage('embridge_asset_entity')->load($asset_id);
         // We need to make sure the asset is permanent at this point.
         if ($asset->isTemporary()) {
             $asset->setPermanent();
             $asset->save();
         }
         /** @var \Drupal\embridge\EmbridgeCatalogInterface $catalog */
         $catalog = $this->entityTypeManager->getStorage('embridge_catalog')->load($form['asset']['#catalog_id']);
         $conversion = $form_state->getValue(['attributes', 'data-conversion']);
         $source_url = $this->assetHelper->getAssetConversionUrl($asset, $catalog->getApplicationId(), $conversion);
         $form_state->setValue(['attributes', 'src'], $source_url);
         $form_state->setValue(['attributes', 'data-entity-uuid'], $asset->uuid());
         $form_state->setValue(['attributes', 'data-entity-type'], 'embridge_asset_entity');
     }
     if ($form_state->getErrors()) {
         unset($form['#prefix'], $form['#suffix']);
         $form['status_messages'] = ['#type' => 'status_messages', '#weight' => -10];
         $response->addCommand(new HtmlCommand('#' . self::AJAX_WRAPPER_ID, $form));
     } else {
         $response->addCommand(new EditorDialogSave($form_state->getValues()));
         $response->addCommand(new CloseModalDialogCommand());
     }
     return $response;
 }
 /**
  * {@inheritdoc}
  *
  * Most block plugins should not override this method. To add submission
  * handling for a specific block type, override BlockBase::blockSubmit().
  *
  * @see \Drupal\Core\Block\BlockBase::blockSubmit()
  */
 public function submitConfigurationForm(array &$form, FormStateInterface $form_state)
 {
     // Process the block's submission handling if no errors occurred only.
     if (!$form_state->getErrors()) {
         $this->configuration['label'] = $form_state->getValue('label');
         $this->configuration['label_display'] = $form_state->getValue('label_display');
         $this->configuration['provider'] = $form_state->getValue('provider');
         $this->configuration['cache'] = $form_state->getValue('cache');
         foreach ($this->getVisibilityConditions() as $condition_id => $condition) {
             // Allow the condition to submit the form.
             $condition_values = (new FormState())->setValues($form_state->getValue(['visibility', $condition_id]));
             $condition->submitConfigurationForm($form, $condition_values);
             // Update the original form values.
             $form_state->setValue(['visibility', $condition_id], $condition_values->getValues());
         }
         $this->blockSubmit($form, $form_state);
     }
 }
Example #20
0
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     // The confirmation step needs no additional validation.
     if ($this->data) {
         return;
     }
     // Decode the submitted import.
     $data = Yaml::decode($form_state->getValue('import'));
     // Validate for config entities.
     if ($form_state->getValue('config_type') !== 'system.simple') {
         $definition = $this->entityManager->getDefinition($form_state->getValue('config_type'));
         $id_key = $definition->getKey('id');
         // If a custom entity ID is specified, override the value in the
         // configuration data being imported.
         if (!$form_state->isValueEmpty('custom_entity_id')) {
             $data[$id_key] = $form_state->getValue('custom_entity_id');
         }
         $entity_storage = $this->entityManager->getStorage($form_state->getValue('config_type'));
         // If an entity ID was not specified, set an error.
         if (!isset($data[$id_key])) {
             $form_state->setErrorByName('import', $this->t('Missing ID key "@id_key" for this @entity_type import.', array('@id_key' => $id_key, '@entity_type' => $definition->getLabel())));
             return;
         }
         $config_name = $definition->getConfigPrefix() . '.' . $data[$id_key];
         // If there is an existing entity, ensure matching ID and UUID.
         if ($entity = $entity_storage->load($data[$id_key])) {
             $this->configExists = $entity;
             if (!isset($data['uuid'])) {
                 $form_state->setErrorByName('import', $this->t('An entity with this machine name already exists but the import did not specify a UUID.'));
                 return;
             }
             if ($data['uuid'] !== $entity->uuid()) {
                 $form_state->setErrorByName('import', $this->t('An entity with this machine name already exists but the UUID does not match.'));
                 return;
             }
         } elseif (isset($data['uuid']) && $entity_storage->loadByProperties(array('uuid' => $data['uuid']))) {
             $form_state->setErrorByName('import', $this->t('An entity with this UUID already exists but the machine name does not match.'));
         }
     } else {
         $config_name = $form_state->getValue('config_name');
         $config = $this->config($config_name);
         $this->configExists = !$config->isNew() ? $config : FALSE;
     }
     // Use ConfigImporter validation.
     if (!$form_state->getErrors()) {
         $source_storage = new StorageReplaceDataWrapper($this->configStorage);
         $source_storage->replaceData($config_name, $data);
         $storage_comparer = new StorageComparer($source_storage, $this->configStorage, $this->configManager);
         if (!$storage_comparer->createChangelist()->hasChanges()) {
             $form_state->setErrorByName('import', $this->t('There are no changes to import.'));
         } else {
             $config_importer = new ConfigImporter($storage_comparer, $this->eventDispatcher, $this->configManager, $this->lock, $this->typedConfigManager, $this->moduleHandler, $this->moduleInstaller, $this->themeHandler, $this->getStringTranslation());
             try {
                 $config_importer->validate();
                 $form_state->set('config_importer', $config_importer);
             } catch (ConfigImporterException $e) {
                 // There are validation errors.
                 $item_list = ['#theme' => 'item_list', '#items' => $config_importer->getErrors(), '#title' => $this->t('The configuration cannot be imported because it failed validation for the following reasons:')];
                 $form_state->setErrorByName('import', $this->renderer->render($item_list));
             }
         }
     }
     // Store the decoded version of the submitted import.
     $form_state->setValueForElement($form['import'], $data);
 }
Example #21
0
 /**
  * Moves form errors from one form state to another.
  *
  * @param \Drupal\Core\Form\FormStateInterface $from
  *   The form state object to move from.
  * @param \Drupal\Core\Form\FormStateInterface $to
  *   The form state object to move to.
  */
 protected function moveFormStateErrors(FormStateInterface $from, FormStateInterface $to)
 {
     foreach ($from->getErrors() as $name => $error) {
         $to->setErrorByName($name, $error);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function massageFormValues(array $values, array $form, FormStateInterface $form_state)
 {
     // Don't do entity saving when we have validation erors.
     if (count($form_state->getErrors()) || !$form_state->isValidationComplete()) {
         return parent::massageFormValues($values, $form, $form_state);
     }
     foreach ($values as $value) {
         if (isset($value['fids'][0]) && isset($value['cropinfo']) && $value['cropinfo']['changed']) {
             $fid = $value['fids'][0];
             $new_crop_info = array('fid' => $fid, 'x' => $value['cropinfo']['x'], 'y' => $value['cropinfo']['y'], 'width' => $value['cropinfo']['width'], 'height' => $value['cropinfo']['height']);
             imagefield_crop_update_file_info($new_crop_info);
             $source = File::load($fid);
             if ($source) {
                 image_path_flush($source->getFileUri());
             }
         }
     }
     return parent::massageFormValues($values, $form, $form_state);
 }
Example #23
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     // Convert any uploaded files from the FID values to data-entity-uuid
     // attributes and set data-entity-type to 'file'.
     $fid = $form_state->getValue(array('fid', 0));
     if (!empty($fid)) {
         $file = $this->fileStorage->load($fid);
         $file_url = file_create_url($file->getFileUri());
         // Transform absolute image URLs to relative image URLs: prevent problems
         // on multisite set-ups and prevent mixed content errors.
         $file_url = file_url_transform_relative($file_url);
         $form_state->setValue(array('attributes', 'src'), $file_url);
         $form_state->setValue(array('attributes', 'data-entity-uuid'), $file->uuid());
         $form_state->setValue(array('attributes', 'data-entity-type'), 'file');
     }
     // When the alt attribute is set to two double quotes, transform it to the
     // empty string: two double quotes signify "empty alt attribute". See above.
     if (trim($form_state->getValue(array('attributes', 'alt'))) === '""') {
         $form_state->setValue(array('attributes', 'alt'), '');
     }
     if ($form_state->getErrors()) {
         unset($form['#prefix'], $form['#suffix']);
         $form['status_messages'] = ['#type' => 'status_messages', '#weight' => -10];
         $response->addCommand(new HtmlCommand('#editor-image-dialog-form', $form));
     } else {
         $response->addCommand(new EditorDialogSave($form_state->getValues()));
         $response->addCommand(new CloseModalDialogCommand());
     }
     return $response;
 }
 /**
  * {@inheritdoc}
  */
 public function submitConfigurationForm(array &$form, FormStateInterface $form_state)
 {
     if (!$form_state->getErrors()) {
         $this->configuration = array_intersect_key($form_state->getValues(), $this->defaultConfiguration());
     }
 }