/** * Entity builder: updates the product status with the submitted value. * * @param string $entity_type * The entity type. * @param \Drupal\commerce_product\Entity\ProductInterface $entity * The product updated with the submitted values. * @param array $form * The complete form array. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * * @see \Drupal\node\NodeForm::form() */ public static function updateStatus($entity_type, EntityInterface $entity, array $form, FormStateInterface $form_state) { $element = $form_state->getTriggeringElement(); if (isset($element['#published_status'])) { $entity->setPublished($element['#published_status']); } }
/** * {@inheritdoc} */ public function submit(array &$form, FormStateInterface $form_state) { if (($trigger = $form_state->getTriggeringElement()) && strpos($trigger['#name'], 'tab_selector_') === 0) { if (!empty($this->widget_ids[$trigger['#widget_id']])) { return $trigger['#widget_id']; } } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { if ($form_state->getTriggeringElement()['#name'] == 'add') { $cached_values = $form_state->getTemporaryValue('wizard'); list(, $route_parameters) = $this->getRelationshipOperationsRouteInfo($cached_values, $this->machine_name, $form_state->getValue('relationships')); $form_state->setRedirect($this->getAddRoute($cached_values), $route_parameters); } }
/** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { if ($triggering_element = $form_state->getTriggeringElement()) { drupal_set_message(t('The clicked button is %name.', ['%name' => $triggering_element['#name']])); } else { drupal_set_message('There is no clicked button.'); } }
/** * {@inheritdoc} */ public function validate(array &$form, FormStateInterface $form_state) { $uploaded_files = $form_state->getValue(['upload'], []); $trigger = $form_state->getTriggeringElement(); // Only validate if we are uploading a file. if (empty($uploaded_files) && $trigger['#value'] == 'Upload') { $form_state->setError($form['widget']['upload'], t('At least one file should be uploaded.')); } }
/** * Submit handler for the views form. * * @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. */ public function viewsFormSubmit(&$form, FormStateInterface $form_state) { $triggering_element = $form_state->getTriggeringElement(); if (!empty($triggering_element['#test_button'])) { $row_index = $triggering_element['#row_index']; $view_args = !empty($this->view->args) ? implode(', ', $this->view->args) : $this->t('no arguments'); drupal_set_message($this->t('The test button at row @row_index for @view_id (@display) View with args: @args was submitted.', ['@display' => $this->view->current_display, '@view_id' => $this->view->id(), '@args' => $view_args, '@row_index' => $row_index])); } }
/** * Ajax callback to fetch the options for target language select. * * @param array $form * The form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The form state. * * @return mixed * Target language select array. */ public function ajaxSourceLanguageSelect(array $form, FormStateInterface $form_state) { if ($el = $form_state->getTriggeringElement()['#value']) { $selected_option = [$el => tmgmt_available_languages()[$el]]; $options = array_diff(tmgmt_available_languages(), $selected_option); $form['info']['target_language']['#options'] = $options; return $form['info']['target_language']; } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { if ($form_state->getTriggeringElement()['#name'] == 'select_id_submit') { $form_state->set('default_type', $form_state->getValue('id')); $form_state->setRebuild(); } else { parent::submitForm($form, $form_state); } }
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'))); } }
/** * Submit callback for remove buttons. * * @param array $form * @param \Drupal\Core\Form\FormStateInterface $form_state */ public static function removeItemSubmit(array &$form, FormStateInterface $form_state) { $triggering_element = $form_state->getTriggeringElement(); // Remove weight of entity being removed. $form_state->unsetValue(['selected', $triggering_element['#attributes']['data-remove-entity']]); // Remove entity itself. $selected_entities =& $form_state->get(['entity_browser', 'selected_entities']); unset($selected_entities[$triggering_element['#attributes']['data-row-id']]); static::saveNewOrder($form_state); $form_state->setRebuild(); }
/** * Button #submit callback: Triggers submission of element forms. * * @param array $form * The form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The form state. */ public static function trigger($form, FormStateInterface $form_state) { $triggered_element = $form_state->getTriggeringElement(); if (!empty($triggered_element['#ief_submit_trigger_all'])) { // The parent form was submitted, process all IEFs and their children. static::doSubmit($form, $form_state); } else { // A specific element was submitted, process it and all of its children. $array_parents = $triggered_element['#array_parents']; $array_parents = array_slice($array_parents, 0, -2); $element = NestedArray::getValue($form, $array_parents); static::doSubmit($element, $form_state); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $triggering_element = $form_state->getTriggeringElement(); // Return early if there are any errors or if a button we're not aware of // submitted the form. if ($form_state->hasAnyErrors() || $triggering_element['#name'] !== 'panels_ipe_submit') { return $form; } // Submit the parent form and save. This mimics the normal behavior of the // submit element in our parent form(s). parent::submitForm($form, $form_state); parent::save($form, $form_state); // Inform the App that we've created a new Block Content entity. $form['#attached']['drupalSettings']['panels_ipe']['new_block_content'] = $this->entity->uuid(); return $form; }
/** * Ajax callback to render a sample of the input date format. * * @param array $form * Form API array structure. * @param \Drupal\Core\Form\FormStateInterface $form_state * Form state information. * * @return AjaxResponse * Ajax response with the rendered sample date using the given format. If * the given format cannot be identified or was empty, the response will * be empty as well. */ public static function ajaxSample(array $form, FormStateInterface $form_state) { $response = new AjaxResponse(); $format_value = NestedArray::getValue($form_state->getValues(), $form_state->getTriggeringElement()['#array_parents']); if (!empty($format_value)) { // Format the date with a custom date format with the given pattern. // The object is not instantiated in an Ajax context, so $this->t() // cannot be used here. $format = t('Displayed as %date_format', array('%date_format' => \Drupal::service('date.formatter')->format(REQUEST_TIME, 'custom', $format_value))); // Return a command instead of a string, since the Ajax framework // automatically prepends an additional empty DIV element for a string, // which breaks the layout. $response->addCommand(new ReplaceCommand('#edit-date-format-suffix', '<small id="edit-date-format-suffix">' . $format . '</small>')); } return $response; }
/** * Implements #element_validate callback for self::fieldSettingsForm(). */ public static function fieldSettingsFormValidate(array $element, FormStateInterface $form_state) { $add_more_button_form_parents = array_merge($element['#array_parents'], ['line_items', 'add_more', 'add']); // Only set the field settings as a value when it is not the "Add more" // button that has been clicked. $triggering_element = $form_state->getTriggeringElement(); if ($triggering_element['#array_parents'] != $add_more_button_form_parents) { $values = $form_state->getValues(); $values = NestedArray::getValue($values, $element['#array_parents']); $line_items_data = []; foreach (PaymentLineItemsInput::getLineItems($element['line_items'], $form_state) as $line_item) { $line_items_data[] = ['plugin_id' => $line_item->getPluginId(), 'plugin_configuration' => $line_item->getConfiguration()]; } $value = ['currency_code' => $values['currency_code'], 'line_items_data' => $line_items_data]; $form_state->setValueForElement($element, $value); } }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { // If the form is rebuilding. if ($form_state->isRebuilding()) { // If an encryption method change triggered the rebuild. if ($form_state->getTriggeringElement()['#name'] == 'encryption_method') { // Update the encryption method plugin. $this->updateEncryptionMethod($form_state); } } elseif ($this->operation == "edit") { // Only when the form is first built. /* @var $encryption_profile \Drupal\encrypt\Entity\EncryptionProfile */ $encryption_profile = $this->entity; $this->originalProfile = clone $encryption_profile; } return parent::buildForm($form, $form_state); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $form['trigger_select'] = ['#type' => 'select', '#title' => 'trigger', '#options' => ['' => '', 'a' => 'Form a', 'b' => 'Form b'], '#required' => TRUE, '#ajax' => array('wrapper' => 'container-id', 'callback' => '::ajaxCallback')]; $form['trigger2'] = $form['trigger_select']; $form['container'] = ['#type' => 'container', '#prefix' => '<div id="container-id">', '#suffix' => '</div>']; $trigger = $form_state->getTriggeringElement(); $mode = $form_state->getValue($trigger['#name']); if ($mode == 'a') { $form['container']['element_a'] = ['#type' => 'select', '#title' => 'A', '#options' => ['1' => 'one', '2' => 'two']]; $form['container']['element_d'] = ['#type' => 'textfield', '#title' => 'D']; } elseif ($mode == 'b') { $form['container']['element_b'] = ['#type' => 'select', '#title' => 'B', '#options' => ['3' => 'three', '4' => 'four']]; } else { $form['container']['element_c'] = ['#type' => 'select', '#title' => 'c', '#options' => ['5' => 'five', '6 ' => 'six']]; } $form['text'] = ['#type' => 'textfield', '#title' => 'dfasd', '#required' => TRUE]; $form['submit'] = ['#type' => 'submit', '#value' => 'Save']; return $form; }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $values = $form_state->getValues(); $taxType = $this->taxTypeImporter->createTaxType($values['tax_type']); try { $taxType->save(); drupal_set_message($this->t('Imported the %label tax type.', ['%label' => $taxType->label()])); $triggeringElement['#name'] = $form_state->getTriggeringElement(); if ($triggeringElement['#name'] == 'import_and_new') { $form_state->setRebuild(); } else { $form_state->setRedirect('entity.commerce_tax_type.collection'); } } catch (\Exception $e) { drupal_set_message($this->t('The %label tax type was not imported.', ['%label' => $taxType->label()]), 'error'); $this->logger('commerce_tax')->error($e); $form_state->setRebuild(); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $form_connection_settings = $form_state->getValue('connection_settings'); switch ($form_state->getTriggeringElement()['#name']) { case 'process_updates': // Save the connection settings to the DB. $filetransfer_backend = $form_connection_settings['authorize_filetransfer_default']; // If the database is available then try to save our settings. We have // to make sure it is available since this code could potentially (will // likely) be called during the installation process, before the // database is set up. try { $connection_settings = array(); foreach ($form_connection_settings[$filetransfer_backend] as $key => $value) { // We do *not* want to store passwords in the database, unless the // backend explicitly says so via the magic #filetransfer_save form // property. Otherwise, we store everything that's not explicitly // marked with #filetransfer_save set to FALSE. if (!isset($form['connection_settings'][$filetransfer_backend][$key]['#filetransfer_save'])) { if ($form['connection_settings'][$filetransfer_backend][$key]['#type'] != 'password') { $connection_settings[$key] = $value; } } elseif ($form['connection_settings'][$filetransfer_backend][$key]['#filetransfer_save']) { $connection_settings[$key] = $value; } } // Set this one as the default authorize method. $this->config('system.authorize')->set('filetransfer_default', $filetransfer_backend); // Save the connection settings minus the password. $this->config('system.authorize')->set('filetransfer_connection_settings_' . $filetransfer_backend, $connection_settings); $filetransfer = $this->getFiletransfer($filetransfer_backend, $form_connection_settings[$filetransfer_backend]); // Now run the operation. $this->runOperation($filetransfer); } catch (\Exception $e) { // If there is no database available, we don't care and just skip // this part entirely. } break; case 'enter_connection_settings': $form_state->setRebuild(); break; case 'change_connection_type': $form_state->setRebuild(); $form_state->unsetValue(array('connection_settings', 'authorize_filetransfer_default')); break; } }
/** * {@inheritdoc} */ public function flagErrors(FieldItemListInterface $items, ConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) { // Never flag validation errors for the remove button. $clicked_button = end($form_state->getTriggeringElement()['#parents']); if ($clicked_button !== 'remove_button') { parent::flagErrors($items, $violations, $form, $form_state); } }
/** * Submit handler to Duplicate a display as another display type. */ public function submitDuplicateDisplayAsType($form, FormStateInterface $form_state) { /** @var \Drupal\views\ViewEntityInterface $view */ $view = $this->entity; $display_id = $this->displayID; // Create the new display. $parents = $form_state->getTriggeringElement()['#parents']; $display_type = array_pop($parents); $new_display_id = $view->duplicateDisplayAsType($display_id, $display_type); // By setting the current display the changed marker will appear on the new // display. $view->getExecutable()->current_display = $new_display_id; $view->cacheSet(); // Redirect to the new display's edit page. $form_state->setRedirect('entity.view.edit_display_form', array('view' => $view->id(), 'display_id' => $new_display_id)); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $types = ViewExecutable::getHandlerTypes(); $view = $form_state->get('view'); $display =& $view->getExecutable()->displayHandlers->get($form_state->get('display_id')); $remember_groups = array(); if (!empty($view->form_cache)) { $old_fields = $view->form_cache['handlers']; } else { $old_fields = $display->getOption($types['filter']['plural']); } $groups = $form_state->getValue('filter_groups'); // Whatever button was clicked, re-calculate field information. $new_fields = $order = array(); // Make an array with the weights foreach ($form_state->getValue('filters') as $field => $info) { // add each value that is a field with a weight to our list, but only if // it has had its 'removed' checkbox checked. if (is_array($info) && empty($info['removed'])) { if (isset($info['weight'])) { $order[$field] = $info['weight']; } if (isset($info['group'])) { $old_fields[$field]['group'] = $info['group']; $remember_groups[$info['group']][] = $field; } } } // Sort the array asort($order); // Create a new list of fields in the new order. foreach (array_keys($order) as $field) { $new_fields[$field] = $old_fields[$field]; } // If the #group property is set on the clicked button, that means we are // either adding or removing a group, not actually updating the filters. $triggering_element = $form_state->getTriggeringElement(); if (!empty($triggering_element['#group'])) { if ($triggering_element['#group'] == 'add') { // Add a new group $groups['groups'][] = 'AND'; } else { // Renumber groups above the removed one down. foreach (array_keys($groups['groups']) as $group_id) { if ($group_id >= $triggering_element['#group']) { $old_group = $group_id + 1; if (isset($groups['groups'][$old_group])) { $groups['groups'][$group_id] = $groups['groups'][$old_group]; if (isset($remember_groups[$old_group])) { foreach ($remember_groups[$old_group] as $id) { $new_fields[$id]['group'] = $group_id; } } } else { // If this is the last one, just unset it. unset($groups['groups'][$group_id]); } } } } // Update our cache with values so that cancel still works the way // people expect. $view->form_cache = ['key' => 'rearrange-filter', 'groups' => $groups, 'handlers' => $new_fields]; // Return to this form except on actual Update. $view->addFormToStack('rearrange-filter', $form_state->get('display_id'), 'filter'); } else { // The actual update button was clicked. Remove the empty groups, and // renumber them sequentially. ksort($remember_groups); $groups['groups'] = static::arrayKeyPlus(array_values(array_intersect_key($groups['groups'], $remember_groups))); // Change the 'group' key on each field to match. Here, $mapping is an // array whose keys are the old group numbers and whose values are the new // (sequentially numbered) ones. $mapping = array_flip(static::arrayKeyPlus(array_keys($remember_groups))); foreach ($new_fields as &$new_field) { $new_field['group'] = $mapping[$new_field['group']]; } // Write the changed handler values. $display->setOption($types['filter']['plural'], $new_fields); $display->setOption('filter_groups', $groups); if (isset($view->form_cache)) { unset($view->form_cache); } } // Store in cache. $view->cacheSet(); }
/** * Ajax handler for multistep buttons. */ public function multistepAjax($form, FormStateInterface $form_state) { $trigger = $form_state->getTriggeringElement(); $op = $trigger['#op']; // Pick the elements that need to receive the ajax-new-content effect. switch ($op) { case 'edit': $updated_rows = array($trigger['#field_name']); $updated_columns = array('plugin'); break; case 'update': case 'cancel': $updated_rows = array($trigger['#field_name']); $updated_columns = array('plugin', 'settings_summary', 'settings_edit'); break; case 'refresh_table': $updated_rows = array_values(explode(' ', $form_state->getValue('refresh_rows'))); $updated_columns = array('settings_summary', 'settings_edit'); break; } foreach ($updated_rows as $name) { foreach ($updated_columns as $key) { $element =& $form['fields'][$name][$key]; $element['#prefix'] = '<div class="ajax-new-content">' . (isset($element['#prefix']) ? $element['#prefix'] : ''); $element['#suffix'] = (isset($element['#suffix']) ? $element['#suffix'] : '') . '</div>'; } } // Return the whole table. return $form['fields']; }
/** * Order pane submit callback: Remove a line item from an order. */ public function removeLineItem($form, FormStateInterface $form_state) { $order =& $form_state->get('order'); $triggering_element = $form_state->getTriggeringElement(); $line_item_id = intval($triggering_element['#return_value']); uc_order_delete_line_item($line_item_id); $order->line_items = $order->getLineItems(); $form_state->setRebuild(); }
/** * Ajax callback to remove a field collection from a multi-valued field. * * @param array $form * @param \Drupal\Core\Form\FormStateInterface $form_state * * @return \Drupal\Core\Ajax\AjaxResponse * An AjaxResponse object. */ function ajaxRemove(array $form, FormStateInterface &$form_state) { // Process user input. $form and $form_state are modified in the process. //\Drupal::formBuilder()->processForm($form['#form_id'], $form, $form_state); // Retrieve the element to be rendered. $trigger = $form_state->getTriggeringElement(); $form_parents = explode('/', $trigger['#ajax']['options']['query']['element_parents']); $address = array_slice($form_parents, 0, -1); $form = NestedArray::getValue($form, $address); $status_messages = array('#theme' => 'status_messages'); $renderer = \Drupal::service('renderer'); $form['#prefix'] = empty($form['#prefix']) ? $renderer->render($status_messages) : $form['#prefix'] . $renderer->render($status_messages); $output = $renderer->render($form); drupal_process_attached($form); // TODO: Preserve javascript. See https://www.drupal.org/node/2502743 . $response = new AjaxResponse(); return $response->addCommand(new ReplaceCommand(NULL, $output)); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $currency_locale = $this->configImporter->importCurrencyLocale($form_state->getValues()['locale']); drupal_set_message($this->t('The %label has been imported.', ['%label' => $currency_locale->label()])); if ($form_state->getTriggeringElement()['#name'] == 'import_edit') { $form_state->setRedirectUrl($currency_locale->urlInfo('edit-form')); } else { $form_state->setRedirectUrl(new Url('entity.currency_locale.collection')); } }
/** * Build all necessary things for child form (form state, etc.). * * @param \Drupal\Core\Entity\EntityFormInterface $controller * Entity form controller for child form. * @param \Drupal\Core\Form\FormStateInterface $form_state * Parent form state object. * @param \Drupal\Core\Entity\EntityInterface $entity * Entity object. * @param string $operation * Operation that is to be performed in inline form. * @param array $parents * Entity form #parents. * * @return \Drupal\Core\Form\FormStateInterface * Child form state object. */ public static function buildChildFormState(EntityFormInterface $controller, FormStateInterface $form_state, EntityInterface $entity, $operation, $parents) { $child_form_state = new FormState(); $child_form_state->addBuildInfo('callback_object', $controller); $child_form_state->addBuildInfo('base_form_id', $controller->getBaseFormID()); $child_form_state->addBuildInfo('form_id', $controller->getFormID()); $child_form_state->addBuildInfo('args', array()); // Copy values to child form. $child_form_state->setCompleteForm($form_state->getCompleteForm()); $child_form_state->setUserInput($form_state->getUserInput()); // Filter out all submitted values that are not directly relevant for this // IEF. Otherwise they might mess things up. $form_state_values = $form_state->getValues(); $form_state_values = static::extractArraySequence($form_state_values, $parents); $child_form_state->setValues($form_state_values); $child_form_state->setStorage($form_state->getStorage()); $value = \Drupal::entityTypeManager()->getStorage('entity_form_display')->load($entity->getEntityTypeId() . '.' . $entity->bundle() . '.' . $operation); $child_form_state->set('form_display', $value); // Since some of the submit handlers are run, redirects need to be disabled. $child_form_state->disableRedirect(); // When a form is rebuilt after Ajax processing, its #build_id and #action // should not change. // @see drupal_rebuild_form() $rebuild_info = $child_form_state->getRebuildInfo(); $rebuild_info['copy']['#build_id'] = TRUE; $rebuild_info['copy']['#action'] = TRUE; $child_form_state->setRebuildInfo($rebuild_info); $child_form_state->set('inline_entity_form', $form_state->get('inline_entity_form')); $child_form_state->set('langcode', $entity->language()->getId()); $child_form_state->set('field', $form_state->get('field')); $child_form_state->setTriggeringElement($form_state->getTriggeringElement()); $child_form_state->setSubmitHandlers($form_state->getSubmitHandlers()); return $child_form_state; }
/** * {@inheritdoc} */ public function &getTriggeringElement() { return $this->mainFormState->getTriggeringElement(); }
/** * {@inheritdoc} */ public function buildResponse(Request $request, array $form, FormStateInterface $form_state, array $commands) { // If the form build ID has changed, issue an Ajax command to update it. if (isset($form['#build_id_old']) && $form['#build_id_old'] !== $form['#build_id']) { $commands[] = new UpdateBuildIdCommand($form['#build_id_old'], $form['#build_id']); } // We need to return the part of the form (or some other content) that needs // to be re-rendered so the browser can update the page with changed // content. It is up to the #ajax['callback'] function of the element (may // or may not be a button) that triggered the Ajax request to determine what // needs to be rendered. $callback = NULL; if (($triggering_element = $form_state->getTriggeringElement()) && isset($triggering_element['#ajax']['callback'])) { $callback = $triggering_element['#ajax']['callback']; } $callback = $form_state->prepareCallback($callback); if (empty($callback) || !is_callable($callback)) { throw new HttpException(500, 'The specified #ajax callback is empty or not callable.'); } $result = call_user_func_array($callback, [&$form, &$form_state, $request]); // If the callback is an #ajax callback, the result is a render array, and // we need to turn it into an AJAX response, so that we can add any commands // we got earlier; typically the UpdateBuildIdCommand when handling an AJAX // submit from a cached page. if ($result instanceof AjaxResponse) { $response = $result; } else { /** @var \Drupal\Core\Ajax\AjaxResponse $response */ $response = $this->ajaxRenderer->renderResponse($result, $request, $this->routeMatch); } foreach ($commands as $command) { $response->addCommand($command, TRUE); } return $response; }
/** * Submit callback: switch a context to data selecor or direct input mode. */ public function switchContextMode(array &$form, FormStateInterface $form_state) { $element_name = $form_state->getTriggeringElement()['#name']; $mode = $form_state->get($element_name); $switched_mode = $mode == 'selector' ? 'input' : 'selector'; $form_state->set($element_name, $switched_mode); $form_state->setRebuild(); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $trigger = $form_state->getTriggeringElement(); switch ($trigger['#name']) { case 'encrypt': if ($to_encrypt = $form_state->getValue('to_encrypt')) { $encrypted_text = $this->encryptService->encrypt($to_encrypt, $this->entity); if ($form_state->getValue('encrypt_base64')) { $encrypted_text = base64_encode($encrypted_text); } $form_state->setValue('encrypted', $encrypted_text); } break; case 'decrypt': if ($to_decrypt = $form_state->getValue('to_decrypt')) { if ($form_state->getValue('decrypt_base64')) { $to_decrypt = base64_decode($to_decrypt); } $decrypted_text = $this->encryptService->decrypt($to_decrypt, $this->entity); $form_state->setValue('decrypted', $decrypted_text); } break; } $form_state->setRebuild(); }