Example #1
1
 /**
  * Form element validation handler for 'name' in form_test_validate_form().
  */
 public function validateName(&$element, FormStateInterface $form_state)
 {
     $triggered = FALSE;
     if ($form_state->getValue('name') == 'element_validate') {
         // Alter the form element.
         $element['#value'] = '#value changed by #element_validate';
         // Alter the submitted value in $form_state.
         $form_state->setValueForElement($element, 'value changed by setValueForElement() in #element_validate');
         $triggered = TRUE;
     }
     if ($form_state->getValue('name') == 'element_validate_access') {
         $form_state->set('form_test_name', $form_state->getValue('name'));
         // Alter the form element.
         $element['#access'] = FALSE;
         $triggered = TRUE;
     } elseif ($form_state->has('form_test_name')) {
         // To simplify this test, just take over the element's value into $form_state.
         $form_state->setValueForElement($element, $form_state->get('form_test_name'));
         $triggered = TRUE;
     }
     if ($triggered) {
         // Output the element's value from $form_state.
         drupal_set_message(t('@label value: @value', array('@label' => $element['#title'], '@value' => $form_state->getValue('name'))));
         // Trigger a form validation error to see our changes.
         $form_state->setErrorByName('');
     }
 }
 public function buildFieldsForm(array &$form, FormStateInterface $form_state)
 {
     if (!$form_state->has('fields')) {
         $form_state->set('fields', $this->configuration['fields']);
     }
     $form_state_fields = $form_state->get('fields');
     // Check if we need to add a new field, or remove one.
     $triggering_element = $form_state->getTriggeringElement();
     if (isset($triggering_element['#name'])) {
         drupal_set_message(t('Changes in this form will not be saved until the %button button at the form bottom is clicked.', array('%button' => t('Save'))), 'warning');
         $button_name = $triggering_element['#name'];
         if ($button_name == 'add_aggregation_field') {
             // Increment $i until the corresponding field is not set, then create
             // the field with that number as suffix.
             for ($i = 1; isset($form_state_fields['search_api_aggregation_' . $i]); ++$i) {
             }
             $form_state_fields['search_api_aggregation_' . $i] = array('label' => '', 'type' => 'union', 'fields' => array());
         } else {
             // Get the field ID from the button name.
             $field_id = substr($button_name, 25);
             unset($form_state_fields[$field_id]);
         }
         $form_state->set('fields', $form_state_fields);
     }
     // Get index type descriptions.
     $type_descriptions = $this->getTypeDescriptions();
     $types = $this->getTypes();
     // Get the available fields for this index.
     $fields = $this->index->getFields(FALSE);
     $field_options = array();
     $field_properties = array();
     // Annotate them so we can show them cleanly in the UI.
     // @todo Use option groups to group fields by datasource?
     /** @var \Drupal\search_api\Item\FieldInterface[] $fields */
     foreach ($fields as $field_id => $field) {
         $field_options[$field_id] = $field->getPrefixedLabel();
         $field_properties[$field_id] = array('#attributes' => array('title' => $field_id), '#description' => $field->getDescription());
     }
     ksort($field_options);
     $form['fields'] = array('#type' => 'container', '#attributes' => array('id' => 'search-api-alter-add-aggregation-field-settings'), '#tree' => TRUE);
     foreach ($form_state_fields as $field_id => $field) {
         $new = !$field['label'];
         $form['fields'][$field_id] = array('#type' => 'details', '#title' => $new ? $this->t('New field') : $field['label'], '#open' => $new);
         $form['fields'][$field_id]['label'] = array('#type' => 'textfield', '#title' => $this->t('New field name'), '#default_value' => $field['label'], '#required' => TRUE);
         $form['fields'][$field_id]['type'] = array('#type' => 'select', '#title' => $this->t('Aggregation type'), '#options' => $types, '#default_value' => $field['type'], '#required' => TRUE);
         $form['fields'][$field_id]['type_descriptions'] = $type_descriptions;
         foreach (array_keys($types) as $type) {
             // @todo This shouldn't rely on undocumented form array structure.
             $form['fields'][$field_id]['type_descriptions'][$type]['#states']['visible'][':input[name="processors[aggregated_field][settings][fields][' . $field_id . '][type]"]']['value'] = $type;
         }
         // @todo Order checked fields first in list?
         $form['fields'][$field_id]['fields'] = array_merge($field_properties, array('#type' => 'checkboxes', '#title' => $this->t('Contained fields'), '#options' => $field_options, '#default_value' => array_combine($field['fields'], $field['fields']), '#attributes' => array('class' => array('search-api-checkboxes-list')), '#required' => TRUE));
         $form['fields'][$field_id]['actions'] = array('#type' => 'actions', 'remove' => array('#type' => 'submit', '#value' => $this->t('Remove field'), '#submit' => array(array($this, 'submitAjaxFieldButton')), '#limit_validation_errors' => array(), '#name' => 'remove_aggregation_field_' . $field_id, '#ajax' => array('callback' => array($this, 'buildAjaxAddFieldButton'), 'wrapper' => 'search-api-alter-add-aggregation-field-settings')));
     }
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, $display_id = NULL)
 {
     if (isset($display_id) && $form_state->has('display_id') && $display_id !== $form_state->get('display_id')) {
         throw new \InvalidArgumentException('Mismatch between $form_state->get(\'display_id\') and $display_id.');
     }
     $this->displayID = $form_state->has('display_id') ? $form_state->get('display_id') : $display_id;
     return parent::buildForm($form, $form_state);
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $key = 'payment_reference_element_prototype_payment';
     if ($form_state->has($key)) {
         $prototype_payment = $form_state->get($key);
         /** @var \Drupal\payment_reference\Plugin\Payment\Type\PaymentReference $payment_type */
         $payment_type = $prototype_payment->getPaymentType();
     } else {
         $entity_type_id = 'user';
         $bundle = 'user';
         $field_name = 'foobarbaz';
         /** @var \Drupal\payment\Entity\PaymentInterface $prototype_payment */
         $prototype_payment = entity_create('payment', array('bundle' => 'payment_reference'));
         $prototype_payment->setCurrencyCode('EUR')->setOwnerId(2)->setLineItems(Generate::createPaymentLineItems());
         /** @var \Drupal\payment_reference\Plugin\Payment\Type\PaymentReference $payment_type */
         $payment_type = $prototype_payment->getPaymentType();
         $payment_type->setEntityTypeId($entity_type_id);
         $payment_type->setBundle($bundle);
         $payment_type->setFieldName($field_name);
         $form_state->set($key, $prototype_payment);
     }
     $form['payment_reference'] = array('#plugin_selector_id' => 'payment_select_list', '#prototype_payment' => $prototype_payment, '#queue_category_id' => $payment_type->getEntityTypeId() . '.' . $payment_type->getBundle() . '.' . $payment_type->getFieldName(), '#queue_owner_id' => 2, '#required' => TRUE, '#title' => 'FooBarBaz', '#type' => 'payment_reference');
     $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, $allowed_selectable_plugin_ids = NULL, $plugin_id = NULL, $tree = FALSE)
 {
     if ($form_state->has('plugin_selector')) {
         $plugin_selector = $form_state->get('plugin_selector');
     } else {
         $selectable_plugin_discovery = new LimitedPluginDiscoveryDecorator($this->selectablePluginType->getPluginManager());
         $selectable_plugin_discovery->setDiscoveryLimit(explode(',', $allowed_selectable_plugin_ids));
         $selectable_plugin_manager = new PluginManagerDecorator($this->selectablePluginType->getPluginManager(), $selectable_plugin_discovery);
         $plugin_selector = $this->pluginSelectorManager->createInstance($plugin_id);
         $plugin_selector->setSelectablePluginType($this->selectablePluginType);
         $plugin_selector->setSelectablePluginDiscovery($selectable_plugin_manager);
         $plugin_selector->setSelectablePluginFactory($selectable_plugin_manager);
         $plugin_selector->setRequired();
         $form_state->set('plugin_selector', $plugin_selector);
     }
     $form['plugin'] = $plugin_selector->buildSelectorForm([], $form_state);
     // Nest the selector in a tree if that's required.
     if ($tree) {
         $form['tree'] = array('#tree' => TRUE);
         $form['tree']['plugin'] = $form['plugin'];
         unset($form['plugin']);
     }
     $form['actions'] = array('#type' => 'actions');
     $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
     return $form;
 }
 /**
  * Stores a plugin selector in the form state.
  *
  * @param \Drupal\Core\Form\FormStateInterface
  * @param \Drupal\plugin\Plugin\Plugin\PluginSelector\PluginSelectorInterface
  *
  * @return string[]
  *   The form state storage key that contains the plugin selector.
  *
  * @throws \InvalidArgumentException
  */
 protected static function setPluginSelector(FormStateInterface $form_state, PluginSelectorInterface $plugin_selector)
 {
     do {
         $key = [get_class(), mt_rand()];
     } while ($form_state->has($key));
     $form_state->set($key, $plugin_selector);
     return $key;
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     if ($form_state->has('json')) {
         $form_state->setResponse(new JsonResponse($form_state->getValues()));
     } else {
         $form_state->disableRedirect();
     }
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, $order = NULL)
 {
     if (!$form_state->has('uc_order')) {
         $form_state->set('uc_order', $order);
     }
     $form['actions'] = array('#type' => 'actions');
     $form['actions']['back'] = array('#type' => 'submit', '#value' => $this->t('Back'), '#submit' => array(array($this, 'back')));
     $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Submit order'), '#button_type' => 'primary');
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function getFormLangcode(FormStateInterface $form_state)
 {
     if (!$form_state->has('langcode')) {
         // Imply a 'view' operation to ensure users edit entities in the same
         // language they are displayed. This allows to keep contextual editing
         // working also for multilingual entities.
         $form_state->set('langcode', $this->entityManager->getTranslationFromContext($this->entity)->language()->getId());
     }
     return $form_state->get('langcode');
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $form['text'] = array('#type' => 'textfield', '#title' => t('Text field'));
     $form['test_submit'] = array('#type' => 'submit', '#value' => t('Submit'));
     $db = Database::getConnection('default');
     $form_state->set('database', $db);
     $form_state->set('database_class', get_class($db));
     if ($form_state->has('database_connection_found')) {
         $form['database']['#markup'] = 'Database connection found';
     }
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     if ($form_state->has('payment_line_item')) {
         $line_item = $form_state->get('payment_line_item');
     } else {
         $line_item = Payment::lineItemManager()->createInstance('payment_basic');
         $form_state->set('payment_line_item', $line_item);
     }
     $form['line_item'] = $line_item->buildConfigurationForm([], $form_state);
     $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
     return $form;
 }
Example #12
0
 /**
  * Uses inline entity form handler to add inline form to the structure.
  *
  * @param array $element
  *   An associative array containing the properties of the element.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  * @param array $complete_form
  *   The complete form structure.
  *
  * @return array
  *   The processed element.
  *
  * @see self::preRenderAjaxForm()
  */
 public static function processEntityForm($element, FormStateInterface $form_state, &$complete_form)
 {
     if (empty($element['#ief_id'])) {
         $element['#ief_id'] = \Drupal::service('uuid')->generate();
     }
     if (empty($element['#entity_type']) && !empty($element['#entity']) && $element['#entity'] instanceof EntityInterface) {
         $element['#entity_type'] = $element['#entity']->entityTypeId();
     }
     if (empty($element['#bundle']) && !empty($element['#entity']) && $element['#entity'] instanceof EntityInterface) {
         $element['#bundle'] = $element['#entity']->bundle();
     }
     // We can't do anything useful if we don't know which entity type/ bundle
     // we're supposed to operate with.
     if (empty($element['#entity_type']) || empty($element['#bundle'])) {
         return;
     }
     /** @var \Drupal\inline_entity_form\InlineFormInterface $ief_handler */
     $ief_handler = \Drupal::entityManager()->getHandler($element['#entity_type'], 'inline_form');
     // IEF handler is a must. If one was not assigned to this entity type we can
     // not proceed.
     if (empty($ief_handler)) {
         return;
     }
     // If entity object is not there we're displaying the add form. We need to
     // create a new entity to be used with it.
     if (empty($element['#entity'])) {
         if ($element['#op'] == 'add') {
             $values = ['langcode' => $element['#language']];
             $bundle_key = \Drupal::entityManager()->getDefinition($element['#entity_type'])->getKey('bundle');
             if ($bundle_key) {
                 $values[$bundle_key] = $element['#bundle'];
             }
             $element['#entity'] = \Drupal::entityManager()->getStorage($element['#entity_type'])->create($values);
         }
     }
     // Put some basic information about IEF into form state.
     $state = $form_state->has(['inline_entity_form', $element['#ief_id']]) ? $form_state->get(['inline_entity_form', $element['#ief_id']]) : [];
     $state += ['op' => $element['#op'], 'entity' => $element['#entity']];
     $form_state->set(['inline_entity_form', $element['#ief_id']], $state);
     $element = $ief_handler->entityForm($element, $form_state);
     // Attach submit callbacks to main submit buttons.
     if ($element['#handle_submit']) {
         static::attachMainSubmit($complete_form);
     }
     return $element;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, $order = NULL)
 {
     if ($processed = $form_state->has('order')) {
         $order = $form_state->get('order');
     } else {
         $form_state->set('order', $order);
     }
     $form['#attributes']['class'][] = 'uc-cart-checkout-form';
     $form['#attached']['library'][] = 'uc_cart/uc_cart.styles';
     $form['panes'] = array('#tree' => TRUE);
     $filter = array('enabled' => FALSE);
     // If the order isn't shippable, remove panes with shippable == TRUE.
     if (!$order->isShippable() && $this->config('uc_cart.settings')->get('delivery_not_shippable')) {
         $filter['shippable'] = TRUE;
     }
     $panes = $this->checkoutPaneManager->getPanes($filter);
     // Invoke the 'prepare' op of enabled panes, but only if their 'process' ops
     // have not been invoked on this request (i.e. when rebuilding after AJAX).
     foreach ($panes as $id => $pane) {
         if (!$form_state->get(['panes', $id, 'prepared'])) {
             $pane->prepare($order, $form, $form_state);
             $form_state->set(['panes', $id, 'prepared'], TRUE);
             $processed = FALSE;
             // Make sure we save the updated order.
         }
     }
     // Load the line items and save the order. We do this after the 'prepare'
     // callbacks of enabled panes have been invoked, because these may have
     // altered the order.
     if (!$processed) {
         $order->line_items = $order->getLineItems();
         $order->save();
     }
     foreach ($panes as $id => $pane) {
         $form['panes'][$id] = $pane->view($order, $form, $form_state);
         $form['panes'][$id] += array('#type' => 'details', '#title' => SafeMarkup::checkPlain($pane->getTitle()), '#id' => $id . '-pane', '#open' => TRUE);
     }
     $form['actions'] = array('#type' => 'actions');
     $form['actions']['cancel'] = array('#type' => 'submit', '#value' => $this->t('Cancel'), '#validate' => array(), '#limit_validation_errors' => array(), '#submit' => array(array($this, 'cancel')));
     $form['actions']['continue'] = array('#type' => 'submit', '#value' => $this->t('Review order'), '#button_type' => 'primary');
     $form_state->loadInclude('uc_store', 'inc', 'includes/uc_ajax_attach');
     $form['#process'][] = 'uc_ajax_process_form';
     $this->session->remove('uc_checkout_review_' . $order->id());
     $this->session->remove('uc_checkout_complete_' . $order->id());
     return $form;
 }
Example #14
0
 /**
  * {@inheritdoc}
  *
  * Builds a form for a single entity field.
  */
 public function buildForm(array $form, FormStateInterface $form_state, EntityInterface $entity = NULL, $field_name = NULL)
 {
     if (!$form_state->has('entity')) {
         $this->init($form_state, $entity, $field_name);
     }
     // Add the field form.
     $form_state->get('form_display')->buildForm($entity, $form, $form_state);
     // Add a dummy changed timestamp field to attach form errors to.
     if ($entity instanceof EntityChangedInterface) {
         $form['changed_field'] = array('#type' => 'hidden', '#value' => $entity->getChangedTime());
     }
     // Add a submit button. Give it a class for easy JavaScript targeting.
     $form['actions'] = array('#type' => 'actions');
     $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Save'), '#attributes' => array('class' => array('quickedit-form-submit')));
     // Simplify it for optimal in-place use.
     $this->simplify($form, $form_state);
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     // Start the form with two checkboxes, to test different defaults, and a
     // textfield, to test more than one element type.
     $form = array('checkbox_1_default_off' => array('#type' => 'checkbox', '#title' => t('This checkbox defaults to unchecked'), '#default_value' => FALSE), 'checkbox_1_default_on' => array('#type' => 'checkbox', '#title' => t('This checkbox defaults to checked'), '#default_value' => TRUE), 'text_1' => array('#type' => 'textfield', '#title' => t('This textfield has a non-empty default value.'), '#default_value' => 'DEFAULT 1'));
     // Provide an 'add more' button that rebuilds the form with an additional two
     // checkboxes and a textfield. The test is to make sure that the rebuild
     // triggered by this button preserves the user input values for the initial
     // elements and initializes the new elements with the correct default values.
     if (!$form_state->has('add_more')) {
         $form['add_more'] = array('#type' => 'submit', '#value' => 'Add more', '#submit' => array('::addMoreSubmitForm'));
     } else {
         $form += array('checkbox_2_default_off' => array('#type' => 'checkbox', '#title' => t('This checkbox defaults to unchecked'), '#default_value' => FALSE), 'checkbox_2_default_on' => array('#type' => 'checkbox', '#title' => t('This checkbox defaults to checked'), '#default_value' => TRUE), 'text_2' => array('#type' => 'textfield', '#title' => t('This textfield has a non-empty default value.'), '#default_value' => 'DEFAULT 2'));
     }
     // A submit button that finishes the form workflow (does not rebuild).
     $form['submit'] = array('#type' => 'submit', '#value' => 'Submit');
     return $form;
 }
Example #16
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     // During the initial form build, add this form object to the form state and
     // allow for initial preparation before form building and processing.
     if (!$form_state->has('entity_form_initialized')) {
         $this->init($form_state);
     }
     $form['#attributes']['class'][] = 'entity-browser-form';
     $form['#browser_parts'] = ['widget_selector' => 'widget_selector', 'widget' => 'widget', 'selection_display' => 'selection_display'];
     $this->entity_browser->getWidgetSelector()->setDefaultWidget($this->getCurrentWidget($form_state));
     $form[$form['#browser_parts']['widget_selector']] = $this->entity_browser->getWidgetSelector()->getForm($form, $form_state);
     $form[$form['#browser_parts']['widget']] = $this->entity_browser->getWidgets()->get($this->getCurrentWidget($form_state))->getForm($form, $form_state, $this->entity_browser->getAdditionalWidgetParameters());
     $form['actions'] = ['submit' => ['#type' => 'submit', '#value' => t('Select'), '#attributes' => ['class' => ['is-entity-browser-submit']]]];
     $form[$form['#browser_parts']['selection_display']] = $this->entity_browser->getSelectionDisplay()->getForm($form, $form_state);
     if ($this->entity_browser->getDisplay() instanceof DisplayAjaxInterface) {
         $this->entity_browser->getDisplay()->addAjax($form);
     }
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     /** @var \Drupal\payment\Entity\PaymentMethodConfigurationInterface $payment_method_configuration */
     $payment_method_configuration = $this->getEntity();
     $definition = $this->paymentMethodConfigurationManager->getDefinition($payment_method_configuration->getPluginId());
     $form['type'] = array('#type' => 'item', '#title' => $this->t('Type'), '#markup' => $definition['label']);
     $form['status'] = array('#type' => 'checkbox', '#title' => $this->t('Enabled'), '#default_value' => $payment_method_configuration->status());
     $form['label'] = array('#type' => 'textfield', '#title' => $this->t('Label'), '#default_value' => $payment_method_configuration->label(), '#maxlength' => 255, '#required' => TRUE);
     $form['id'] = array('#type' => 'machine_name', '#default_value' => $payment_method_configuration->id(), '#maxlength' => 255, '#required' => TRUE, '#machine_name' => array('source' => array('label'), 'exists' => array($this, 'paymentMethodConfigurationIdExists')), '#disabled' => !$payment_method_configuration->isNew());
     $form['owner'] = array('#target_type' => 'user', '#type' => 'entity_autocomplete', '#title' => $this->t('Owner'), '#default_value' => $payment_method_configuration->getOwner() ? $payment_method_configuration->getOwner() : $this->currentUser, '#required' => TRUE);
     if ($form_state->has('payment_method_configuration')) {
         $payment_method_configuration_plugin = $form_state->get('payment_method_configuration');
     } else {
         $payment_method_configuration_plugin = $this->paymentMethodConfigurationManager->createInstance($payment_method_configuration->getPluginId(), $payment_method_configuration->getPluginConfiguration());
         $form_state->set('payment_method_configuration', $payment_method_configuration_plugin);
     }
     $form['plugin_form'] = array('#tree' => TRUE) + $payment_method_configuration_plugin->buildConfigurationForm([], $form_state);
     return parent::form($form, $form_state);
 }
Example #18
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(OrderInterface $order, array $form, FormStateInterface $form_state)
 {
     $form['add_product_button'] = array('#type' => 'submit', '#value' => $this->t('Add product'), '#submit' => array(array($this, 'productSelectSearch')), '#ajax' => array('callback' => array($this, 'ajaxCallback'), 'wrapper' => 'product-controls'));
     $form['add_blank_line_button'] = array('#type' => 'submit', '#value' => $this->t('Add blank line'), '#submit' => array(array($this, 'addBlank')), '#ajax' => array('callback' => array($this, 'ajaxCallback'), 'wrapper' => 'product-controls'));
     $form['product_controls'] = array('#tree' => TRUE, '#prefix' => '<div id="product-controls">', '#suffix' => '</div>');
     $controls = array();
     if ($form_state->has('products_action')) {
         switch ($form_state->get('products_action')) {
             case 'select':
                 $controls = $this->productSelectForm($form['product_controls'], $form_state, $order);
                 break;
             case 'add_product':
                 $controls = $this->addProductForm($form['product_controls'], $form_state, $order, $form_state->get('node'));
                 break;
         }
     }
     $form['product_controls'] += $controls;
     $form += $this->editProductsForm($form, $form_state, $order->products);
     return $form;
 }
 /**
  * Gets the plugin selector for a field item's elements.
  *
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  * @param mixed[] $element
  *   The field widget's form elements.
  *
  * @return \Drupal\plugin\Plugin\Plugin\PluginSelector\PluginSelectorInterface
  */
 protected static function getPluginSelector(FormStateInterface $form_state, array $element)
 {
     /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
     $field_definition = $element['#field_definition'];
     $form_state_key = sprintf('plugin_selector:%s:%d', $field_definition->getName(), $element['#delta']);
     if ($form_state->has($form_state_key)) {
         $plugin_selector = $form_state->get($form_state_key);
     } else {
         /** @var \Drupal\plugin\PluginType\PluginTypeManagerInterface $plugin_type_manager */
         $plugin_type_manager = \Drupal::service('plugin.plugin_type_manager');
         /** @var \Drupal\plugin\Plugin\Plugin\PluginSelector\PluginSelectorManagerInterface $plugin_selector_manager */
         $plugin_selector_manager = \Drupal::service('plugin.manager.plugin.plugin_selector');
         $plugin_type = $plugin_type_manager->getPluginType($element['#plugin_type_id']);
         $plugin_selector = $plugin_selector_manager->createInstance($element['#plugin_selector_id']);
         $plugin_selector->setRequired($field_definition->isRequired());
         $plugin_selector->setSelectablePluginType($plugin_type);
         $plugin_selector->setKeepPreviouslySelectedPlugins();
         if ($element['#selected_plugin']) {
             $plugin_selector->setSelectedPlugin($element['#selected_plugin']);
         }
         $form_state->set($form_state_key, $plugin_selector);
     }
     return $plugin_selector;
 }
 /**
  * Returns the widget object used in default value form.
  *
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The form state of the (entire) configuration form.
  *
  * @return \Drupal\Core\Field\WidgetInterface
  *   A Widget object.
  */
 protected function defaultValueWidget(FormStateInterface $form_state)
 {
     if (!$form_state->has('default_value_widget')) {
         $entity = $this->getEntity();
         // Force a non-required widget.
         $this->getFieldDefinition()->required = FALSE;
         $this->getFieldDefinition()->description = '';
         // Use the widget currently configured for the 'default' form mode, or
         // fallback to the default widget for the field type.
         $entity_form_display = entity_get_form_display($entity->getEntityTypeId(), $entity->bundle(), 'default');
         $widget = $entity_form_display->getRenderer($this->getFieldDefinition()->getName());
         if (!$widget) {
             $widget = \Drupal::service('plugin.manager.field.widget')->getInstance(array('field_definition' => $this->getFieldDefinition()));
         }
         $form_state->set('default_value_widget', $widget);
     }
     return $form_state->get('default_value_widget');
 }
Example #21
0
 /**
  * Wrapper for handling AJAX forms.
  *
  * Wrapper around \Drupal\Core\Form\FormBuilderInterface::buildForm() to
  * handle some AJAX stuff automatically.
  * This makes some assumptions about the client.
  *
  * @param \Drupal\Core\Form\FormInterface|string $form_class
  *   The value must be one of the following:
  *   - The name of a class that implements \Drupal\Core\Form\FormInterface.
  *   - An instance of a class that implements \Drupal\Core\Form\FormInterface.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse|string|array
  *   Returns one of three possible values:
  *   - A \Drupal\Core\Ajax\AjaxResponse object.
  *   - The rendered form, as a string.
  *   - A render array with the title in #title and the rendered form in the
  *   #markup array.
  */
 protected function ajaxFormWrapper($form_class, FormStateInterface &$form_state)
 {
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = \Drupal::service('renderer');
     // This won't override settings already in.
     if (!$form_state->has('rerender')) {
         $form_state->set('rerender', FALSE);
     }
     $ajax = $form_state->get('ajax');
     // Do not overwrite if the redirect has been disabled.
     if (!$form_state->isRedirectDisabled()) {
         $form_state->disableRedirect($ajax);
     }
     $form_state->disableCache();
     // Builds the form in a render context in order to ensure that cacheable
     // metadata is bubbled up.
     $render_context = new RenderContext();
     $callable = function () use($form_class, &$form_state) {
         return \Drupal::formBuilder()->buildForm($form_class, $form_state);
     };
     $form = $renderer->executeInRenderContext($render_context, $callable);
     if (!$render_context->isEmpty()) {
         BubbleableMetadata::createFromRenderArray($form)->merge($render_context->pop())->applyTo($form);
     }
     $output = $renderer->renderRoot($form);
     drupal_process_attached($form);
     // These forms have the title built in, so set the title here:
     $title = $form_state->get('title') ?: '';
     if ($ajax && (!$form_state->isExecuted() || $form_state->get('rerender'))) {
         // If the form didn't execute and we're using ajax, build up an
         // Ajax command list to execute.
         $response = new AjaxResponse();
         // Attach the library necessary for using the OpenModalDialogCommand and
         // set the attachments for this Ajax response.
         $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
         $response->setAttachments($form['#attached']);
         $display = '';
         $status_messages = array('#type' => 'status_messages');
         if ($messages = $renderer->renderRoot($status_messages)) {
             $display = '<div class="views-messages">' . $messages . '</div>';
         }
         $display .= $output;
         $options = array('dialogClass' => 'views-ui-dialog', 'width' => '75%');
         $response->addCommand(new OpenModalDialogCommand($title, $display, $options));
         if ($section = $form_state->get('#section')) {
             $response->addCommand(new Ajax\HighlightCommand('.' . Html::cleanCssIdentifier($section)));
         }
         return $response;
     }
     return $title ? ['#title' => $title, '#markup' => $output] : $output;
 }
Example #22
0
 /**
  * Form constructor to edit an entire menu tree at once.
  *
  * Shows for one menu the menu links accessible to the current user and
  * relevant operations.
  *
  * This form constructor can be integrated as a section into another form. It
  * relies on the following keys in $form_state:
  * - menu: A menu entity.
  * - menu_overview_form_parents: An array containing the parent keys to this
  *   form.
  * Forms integrating this section should call menu_overview_form_submit() from
  * their form submit handler.
  */
 protected function buildOverviewForm(array &$form, FormStateInterface $form_state)
 {
     // Ensure that menu_overview_form_submit() knows the parents of this form
     // section.
     if (!$form_state->has('menu_overview_form_parents')) {
         $form_state->set('menu_overview_form_parents', []);
     }
     $form['#attached']['library'][] = 'menu_ui/drupal.menu_ui.adminforms';
     $tree = $this->menuTree->load($this->entity->id(), new MenuTreeParameters());
     // We indicate that a menu administrator is running the menu access check.
     $this->getRequest()->attributes->set('_menu_admin', TRUE);
     $manipulators = array(array('callable' => 'menu.default_tree_manipulators:checkAccess'), array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'));
     $tree = $this->menuTree->transform($tree, $manipulators);
     $this->getRequest()->attributes->set('_menu_admin', FALSE);
     // Determine the delta; the number of weights to be made available.
     $count = function (array $tree) {
         $sum = function ($carry, MenuLinkTreeElement $item) {
             return $carry + $item->count();
         };
         return array_reduce($tree, $sum);
     };
     $delta = max($count($tree), 50);
     $form['links'] = array('#type' => 'table', '#theme' => 'table__menu_overview', '#header' => array($this->t('Menu link'), array('data' => $this->t('Enabled'), 'class' => array('checkbox')), $this->t('Weight'), array('data' => $this->t('Operations'), 'colspan' => 3)), '#attributes' => array('id' => 'menu-overview'), '#tabledrag' => array(array('action' => 'match', 'relationship' => 'parent', 'group' => 'menu-parent', 'subgroup' => 'menu-parent', 'source' => 'menu-id', 'hidden' => TRUE, 'limit' => \Drupal::menuTree()->maxDepth() - 1), array('action' => 'order', 'relationship' => 'sibling', 'group' => 'menu-weight')));
     $form['links']['#empty'] = $this->t('There are no menu links yet. <a href=":url">Add link</a>.', [':url' => $this->url('entity.menu.add_link_form', ['menu' => $this->entity->id()], ['query' => ['destination' => $this->entity->url('edit-form')]])]);
     $links = $this->buildOverviewTreeForm($tree, $delta);
     foreach (Element::children($links) as $id) {
         if (isset($links[$id]['#item'])) {
             $element = $links[$id];
             $form['links'][$id]['#item'] = $element['#item'];
             // TableDrag: Mark the table row as draggable.
             $form['links'][$id]['#attributes'] = $element['#attributes'];
             $form['links'][$id]['#attributes']['class'][] = 'draggable';
             $form['links'][$id]['#item'] = $element['#item'];
             // TableDrag: Sort the table row according to its existing/configured weight.
             $form['links'][$id]['#weight'] = $element['#item']->link->getWeight();
             // Add special classes to be used for tabledrag.js.
             $element['parent']['#attributes']['class'] = array('menu-parent');
             $element['weight']['#attributes']['class'] = array('menu-weight');
             $element['id']['#attributes']['class'] = array('menu-id');
             $form['links'][$id]['title'] = array(array('#theme' => 'indentation', '#size' => $element['#item']->depth - 1), $element['title']);
             $form['links'][$id]['enabled'] = $element['enabled'];
             $form['links'][$id]['enabled']['#wrapper_attributes']['class'] = array('checkbox', 'menu-enabled');
             $form['links'][$id]['weight'] = $element['weight'];
             // Operations (dropbutton) column.
             $form['links'][$id]['operations'] = $element['operations'];
             $form['links'][$id]['id'] = $element['id'];
             $form['links'][$id]['parent'] = $element['parent'];
         }
     }
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     // During the initial form build, add this form object to the form state and
     // allow for initial preparation before form building and processing.
     if (!$form_state->has('entity_form_initialized')) {
         $this->init($form_state);
     }
     // Retrieve the form array using the possibly updated entity in form state.
     $form = $this->form($form, $form_state);
     // Retrieve and add the form actions array.
     $actions = $this->actionsElement($form, $form_state);
     if (!empty($actions)) {
         $form['actions'] = $actions;
     }
     return $form;
 }
Example #24
0
 /**
  * {@inheritdoc}
  */
 public static function process(array &$element, FormStateInterface $form_state, array &$complete_form)
 {
     $settings = $element['#filefield_sources_settings']['source_attach'];
     $field_name = $element['#field_name'];
     $instance = entity_load('field_config', $element['#entity_type'] . '.' . $element['#bundle'] . '.' . $field_name);
     $element['filefield_attach'] = array('#weight' => 100.5, '#theme' => 'filefield_sources_element', '#source_id' => 'attach', '#filefield_source' => TRUE);
     $path = static::getDirectory($settings);
     $options = static::getAttachOptions($path);
     // If we have built this element before, append the list of options that we
     // had previously. This allows files to be deleted after copying them and
     // still be considered a valid option during the validation and submit.
     $triggering_element = $form_state->getTriggeringElement();
     $property = array('filefield_sources', $field_name, 'attach_options');
     if (!isset($triggering_element) && $form_state->has($property)) {
         $attach_options = $form_state->get($property);
         $options = $options + $attach_options;
     } else {
         $form_state->set(array('filefield_sources', $field_name, 'attach_options'), $options);
     }
     $description = t('This method may be used to attach files that exceed the file size limit. Files may be attached from the %directory directory on the server, usually uploaded through FTP.', array('%directory' => realpath($path)));
     // Error messages.
     if ($options === FALSE || empty($settings['path'])) {
         $attach_message = t('A file attach directory could not be located.');
         $attach_description = t('Please check your settings for the %field field.', array('%field' => $instance->getLabel()));
     } elseif (!count($options)) {
         $attach_message = t('There currently are no files to attach.');
         $attach_description = $description;
     }
     if (isset($attach_message)) {
         $element['filefield_attach']['attach_message'] = array('#markup' => $attach_message);
         $element['filefield_attach']['#description'] = $attach_description;
     } else {
         $validators = $element['#upload_validators'];
         if (isset($validators['file_validate_size'])) {
             unset($validators['file_validate_size']);
         }
         $description .= '<br />' . filefield_sources_element_validation_help($validators);
         $element['filefield_attach']['filename'] = array('#type' => 'select', '#options' => $options);
         $element['filefield_attach']['#description'] = $description;
     }
     $class = '\\Drupal\\file\\Element\\ManagedFile';
     $ajax_settings = ['callback' => [$class, 'uploadAjaxCallback'], 'options' => ['query' => ['element_parents' => implode('/', $element['#array_parents'])]], 'wrapper' => $element['#id'] . '-ajax-wrapper', 'effect' => 'fade', 'progress' => ['type' => $element['#progress_indicator'], 'message' => $element['#progress_message']]];
     $element['filefield_attach']['attach'] = ['#name' => implode('_', $element['#parents']) . '_attach', '#type' => 'submit', '#value' => t('Attach'), '#validate' => [], '#submit' => ['filefield_sources_field_submit'], '#limit_validation_errors' => [$element['#parents']], '#ajax' => $ajax_settings];
     return $element;
 }
Example #25
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     // During the initial form build, add this form object to the form state and
     // allow for initial preparation before form building and processing.
     if (!$form_state->has('entity_form_initialized')) {
         $this->init($form_state);
     }
     // Ensure that edit forms have the correct cacheability metadata so they can
     // be cached.
     if (!$this->entity->isNew()) {
         \Drupal::service('renderer')->addCacheableDependency($form, $this->entity);
     }
     // Retrieve the form array using the possibly updated entity in form state.
     $form = $this->form($form, $form_state);
     // Retrieve and add the form actions array.
     $actions = $this->actionsElement($form, $form_state);
     if (!empty($actions)) {
         $form['actions'] = $actions;
     }
     return $form;
 }
Example #26
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     drupal_set_message("Title: " . Html::escape($form_state->getValue('title')));
     drupal_set_message("Form constructions: " . $_SESSION['constructions']);
     if ($form_state->has(['thing', 'changed'])) {
         drupal_set_message("The thing has been changed.");
     }
     $form_state->setRedirect('<front>');
 }
Example #27
0
  /**
   * @inheritdoc
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // Display page 2 if $form_state->get('page_num') == 2.
    if ($form_state->has('page_num') && $form_state->get('page_num') == 2) {
      return $this->buildFormPageTwo($form, $form_state);
    }

    // Otherwise build page 1.
    $form_state->set('page_num', 1);

    $form['#title'] = $this->t('Content types');
    $form['description'] = array(
      '#type' => 'item',
      '#title' => $this->t('Create a content type by importing Schema.Org entity type.'),
    );

    $form['rdf-type'] = array(
      '#title' => $this->t('Type'),
      '#id' => 'rdf-predicate',
      '#type' => 'select',
      '#required' => TRUE,
      '#options' => $this->converter->getListTypes(),
      '#empty_option' => '',
      '#default_value' => $form_state->getValue('rdf-type', ''),
      '#attached' => array(
        'library' => array(
          'rdfui/drupal.rdfui.autocomplete',
        ),
      ),
      '#description' => $this->t('Specify the type you want to associated to this content type e.g. Article, Blog, etc.'),
    );

    $form['actions'] = array('#type' => 'actions');
    $form['actions']['next'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Next >>'),
      '#button_type' => 'primary',
      '#submit' => array(array($this, 'nextSubmit')),
      '#validate' => array(array($this, 'nextValidate')),
    );
    return $form;
  }
 /**
  * Gets the parent payment status selector.
  *
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *
  * @return \Drupal\plugin\Plugin\Plugin\PluginSelector\PluginSelectorInterface
  */
 protected function getParentPaymentStatusSelector(FormStateInterface $form_state)
 {
     $key = 'parent_payment_status_selector';
     if ($form_state->has($key)) {
         $plugin_selector = $form_state->get($key);
     } else {
         $plugin_selector = $this->pluginSelectorManager->createInstance('payment_select_list');
         $plugin_selector->setSelectablePluginType($this->pluginTypeManager->getPluginType('payment_status'));
         $plugin_selector->setCollectPluginConfiguration(FALSE);
         $plugin_selector->setLabel($this->t('Parent status'));
         $form_state->set($key, $plugin_selector);
     }
     return $plugin_selector;
 }
Example #29
0
 /**
  * Ajax callback for applying shipping rates.
  */
 public function updateOrderRates($form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     // Update shipping line item.
     if ($form_state->has('uc_quote')) {
         $lid = $form_state->get(['uc_quote', 'lid']);
         $form['line_items'][$lid]['title']['#value'] = $form_state->get(['uc_quote', 'title']);
         $form['line_items'][$lid]['amount']['#value'] = $form_state->get(['uc_quote', 'amount']);
     }
     $response->addCommand(new ReplaceCommand('#order-line-items', trim(drupal_render($form['line_items']))));
     // Reset shipping form.
     $response->addCommand(new ReplaceCommand('#quote', trim(drupal_render($form['quotes']['quotes']))));
     $status_messages = array('#type' => 'status_messages');
     $response->addCommand(new PrependCommand('#quote', drupal_render($status_messages)));
     return $response;
 }
Example #30
0
 /**
  * Initializes form language code values.
  *
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 protected function initFormLangcodes(FormStateInterface $form_state)
 {
     // Store the entity default language to allow checking whether the form is
     // dealing with the original entity or a translation.
     if (!$form_state->has('entity_default_langcode')) {
         $form_state->set('entity_default_langcode', $this->entity->getUntranslated()->language()->getId());
     }
     // This value might have been explicitly populated to work with a particular
     // entity translation. If not we fall back to the most proper language based
     // on contextual information.
     if (!$form_state->has('langcode')) {
         // Imply a 'view' operation to ensure users edit entities in the same
         // language they are displayed. This allows to keep contextual editing
         // working also for multilingual entities.
         $form_state->set('langcode', $this->entityManager->getTranslationFromContext($this->entity)->language()->getId());
     }
 }