/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { if ($form_state->isRebuilding()) { $form_state->setUserInput(array()); } // Initialize $storage = $form_state->getStorage(); if (empty($storage)) { $user_input = $form_state->getUserInput(); if (empty($user_input)) { $_SESSION['constructions'] = 0; } // Put the initial thing into the storage $storage = ['thing' => ['title' => 'none', 'value' => '']]; $form_state->setStorage($storage); } // Count how often the form is constructed. $_SESSION['constructions']++; drupal_set_message("Form constructions: " . $_SESSION['constructions']); $form['title'] = array('#type' => 'textfield', '#title' => 'Title', '#default_value' => $storage['thing']['title'], '#required' => TRUE); $form['value'] = array('#type' => 'textfield', '#title' => 'Value', '#default_value' => $storage['thing']['value'], '#element_validate' => array('::elementValidateValueCached')); $form['continue_button'] = array('#type' => 'button', '#value' => 'Reset'); $form['continue_submit'] = array('#type' => 'submit', '#value' => 'Continue submit', '#submit' => array('::continueSubmitForm')); $form['submit'] = array('#type' => 'submit', '#value' => 'Save'); if (\Drupal::request()->get('cache')) { // Manually activate caching, so we can test that the storage keeps working // when it's enabled. $form_state->setCached(); } if ($this->getRequest()->get('immutable')) { $form_state->addBuildInfo('immutable', TRUE); } return $form; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { // Don't show the form when batch operations are in progress. if ($batch = batch_get() && isset($batch['current_set'])) { return array('#theme' => ''); } // Make sure that we validate because this form might be submitted // multiple times per page. $form_state->setValidationEnforced(); /** @var \Drupal\views\ViewExecutable $view */ $view = $form_state->get('view'); $display =& $form_state->get('display'); $form_state->setUserInput($view->getExposedInput()); // Let form plugins know this is for exposed widgets. $form_state->set('exposed', TRUE); // Check if the form was already created if ($cache = $this->exposedFormCache->getForm($view->storage->id(), $view->current_display)) { return $cache; } $form['#info'] = array(); // Go through each handler and let it generate its exposed widget. foreach ($view->display_handler->handlers as $type => $value) { /** @var \Drupal\views\Plugin\views\ViewsHandlerInterface $handler */ foreach ($view->{$type} as $id => $handler) { if ($handler->canExpose() && $handler->isExposed()) { // Grouped exposed filters have their own forms. // Instead of render the standard exposed form, a new Select or // Radio form field is rendered with the available groups. // When an user choose an option the selected value is split // into the operator and value that the item represents. if ($handler->isAGroup()) { $handler->groupForm($form, $form_state); $id = $handler->options['group_info']['identifier']; } else { $handler->buildExposedForm($form, $form_state); } if ($info = $handler->exposedInfo()) { $form['#info']["{$type}-{$id}"] = $info; } } } } $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array('#name' => '', '#type' => 'submit', '#value' => $this->t('Apply'), '#id' => drupal_html_id('edit-submit-' . $view->storage->id())); $form['#action'] = _url($view->display_handler->getUrl()); $form['#theme'] = $view->buildThemeFunctions('views_exposed_form'); $form['#id'] = drupal_clean_css_identifier('views_exposed_form-' . String::checkPlain($view->storage->id()) . '-' . String::checkPlain($display['id'])); // $form['#attributes']['class'] = array('views-exposed-form'); /** @var \Drupal\views\Plugin\views\exposed_form\ExposedFormPluginBase $exposed_form_plugin */ $exposed_form_plugin = $form_state->get('exposed_form_plugin'); $exposed_form_plugin->exposedFormAlter($form, $form_state); // Save the form. $this->exposedFormCache->setForm($view->storage->id(), $view->current_display, $form); return $form; }
protected function valueForm(&$form, FormStateInterface $form_state) { $users = $this->value ? User::loadMultiple($this->value) : array(); $default_value = EntityAutocomplete::getEntityLabels($users); $form['value'] = array('#type' => 'entity_autocomplete', '#title' => $this->t('Usernames'), '#description' => $this->t('Enter a comma separated list of user names.'), '#target_type' => 'user', '#tags' => TRUE, '#default_value' => $default_value, '#process_default_value' => FALSE); $user_input = $form_state->getUserInput(); if ($form_state->get('exposed') && !isset($user_input[$this->options['expose']['identifier']])) { $user_input[$this->options['expose']['identifier']] = $default_value; $form_state->setUserInput($user_input); } }
/** * Provide a simple textfield for equality */ protected function valueForm(&$form, FormStateInterface $form_state) { $form['value'] = array('#type' => 'textfield', '#title' => $this->t('Value'), '#size' => 30, '#default_value' => $this->value); if ($exposed = $form_state->get('exposed')) { $identifier = $this->options['expose']['identifier']; $user_input = $form_state->getUserInput(); if (!isset($user_input[$identifier])) { $user_input[$identifier] = $this->value; $form_state->setUserInput($user_input); } } }
/** * {@inheritdoc} */ public function view(OrderInterface $order, array $form, FormStateInterface $form_state) { $contents['#attached']['library'][] = 'uc_payment/uc_payment.styles'; if ($this->configuration['show_preview']) { $contents['line_items'] = array('#theme' => 'uc_payment_totals', '#order' => $order, '#weight' => -20); } // Ensure that the form builder uses #default_value to determine which // button should be selected after an ajax submission. This is // necessary because the previously selected value may have become // unavailable, which would result in an invalid selection. $input = $form_state->getUserInput(); unset($input['panes']['payment']['payment_method']); $form_state->setUserInput($input); $options = array(); $methods = PaymentMethod::loadMultiple(); uasort($methods, 'Drupal\\uc_payment\\Entity\\PaymentMethod::sort'); foreach ($methods as $method) { // $set = rules_config_load('uc_payment_method_' . $method['id']); // if ($set && !$set->execute($order)) { // continue; // } if ($method->status()) { $options[$method->id()] = $method->getDisplayLabel(); } } \Drupal::moduleHandler()->alter('uc_payment_method_checkout', $options, $order); if (!$options) { $contents['#description'] = $this->t('Checkout cannot be completed without any payment methods enabled. Please contact an administrator to resolve the issue.'); $options[''] = $this->t('No payment methods available'); } elseif (count($options) > 1) { $contents['#description'] = $this->t('Select a payment method from the following options.'); } if (!$order->getPaymentMethodId() || !isset($options[$order->getPaymentMethodId()])) { $order->setPaymentMethodId(key($options)); } $contents['payment_method'] = array('#type' => 'radios', '#title' => $this->t('Payment method'), '#title_display' => 'invisible', '#options' => $options, '#default_value' => $order->getPaymentMethodId(), '#disabled' => count($options) == 1, '#required' => TRUE, '#ajax' => array('callback' => array($this, 'ajaxRender'), 'wrapper' => 'payment-details', 'progress' => array('type' => 'throbber'))); // If there are no payment methods available, this will be ''. if ($order->getPaymentMethodId()) { $plugin = $this->paymentMethodManager->createFromOrder($order); $definition = $plugin->getPluginDefinition(); $contents['details'] = array('#prefix' => '<div id="payment-details" class="clearfix ' . Html::cleanCssIdentifier('payment-details-' . $definition['id']) . '">', '#markup' => $this->t('Continue with checkout to complete payment.'), '#suffix' => '</div>'); try { $details = $plugin->cartDetails($order, $form, $form_state); if ($details) { unset($contents['details']['#markup']); $contents['details'] += $details; } } catch (PluginException $e) { } } return $contents; }
/** * Load the values from the bundle into the user input. * Used during Ajax callback since updating #default_values is ignored. * @param $bundle_name * @param \Drupal\Core\Form\FormStateInterface $form_state */ protected function loadBundleValues(FormStateInterface &$form_state, $current_bundle, $enabled_methods, $methods_weight) { $input = $form_state->getUserInput(); $input['bundle']['name'] = $current_bundle->isDefault() ? '' : $current_bundle->getName(); $input['bundle']['machine_name'] = $current_bundle->getMachineName(); $input['bundle']['description'] = $current_bundle->isDefault() ? '' : $current_bundle->getDescription(); $input['bundle']['is_profile'] = $current_bundle->isProfile() ? 1 : null; $input['bundle']['profile_name'] = $current_bundle->isProfile() ? $current_bundle->getProfileName() : ''; foreach ($methods_weight as $method_id => $weight) { $enabled = isset($enabled_methods[$method_id]); $input['weight'][$method_id] = $weight; $input['enabled'][$method_id] = $enabled ? 1 : null; } $form_state->setUserInput($input); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { if ($form_state->hasValue('date')) { $userInput = $form_state->getUserInput(); $userInput['result'] = 'Date Set'; $form_state->setUserInput($userInput); } else { $form_state->setValue('date', date('Y-m-d', REQUEST_TIME)); $form_state->setValue('result', 'date not set'); $result = 'Date Not Set'; } $form['ajax_wrapper'] = ['#type' => 'container', '#attributes' => ['id' => 'ajax_wrapper']]; $form['ajax_wrapper']['date'] = ['#type' => 'date', '#title' => $this->t('Date')]; $form['ajax_wrapper']['submit_button'] = ['#type' => 'submit', '#value' => 'Load', '#ajax' => ['callback' => [$this, 'ajaxFormCallback']]]; $form['ajax_wrapper']['result'] = ['#type' => 'textfield', '#title' => $this->t('Result'), '#default_value' => $result]; return $form; }
/** * {@inheritdoc} */ public function view(OrderInterface $order, array $form, FormStateInterface $form_state) { $user = \Drupal::currentUser(); $pane = $this->pluginDefinition['id']; $source = $this->sourcePaneId(); $contents['#description'] = $this->getDescription(); if ($source != $pane) { $contents['copy_address'] = array('#type' => 'checkbox', '#title' => $this->getCopyAddressText(), '#default_value' => $this->configuration['default_same_address'], '#ajax' => array('callback' => array($this, 'ajaxRender'), 'wrapper' => $pane . '-address-pane', 'progress' => array('type' => 'throbber'))); } if ($user->isAuthenticated() && ($addresses = uc_select_addresses($user->id(), $pane))) { $contents['select_address'] = array('#type' => 'select', '#title' => t('Saved addresses'), '#options' => $addresses['#options'], '#ajax' => array('callback' => array($this, 'ajaxRender'), 'wrapper' => $pane . '-address-pane', 'progress' => array('type' => 'throbber')), '#states' => array('invisible' => array('input[name="panes[' . $pane . '][copy_address]"]' => array('checked' => TRUE)))); } $contents['address'] = array('#type' => 'uc_address', '#default_value' => $order->getAddress($pane), '#prefix' => '<div id="' . $pane . '-address-pane">', '#suffix' => '</div>'); if ($form_state->hasValue(['panes', $pane, 'copy_address'])) { $contents['address']['#hidden'] = !$form_state->isValueEmpty(['panes', $pane, 'copy_address']); } elseif (isset($contents['copy_address'])) { $contents['address']['#hidden'] = $this->configuration['default_same_address']; } if ($element = $form_state->getTriggeringElement()) { $input = $form_state->getUserInput(); if ($element['#name'] == "panes[{$pane}][copy_address]") { $address =& $form_state->getValue(['panes', $source]); foreach ($address as $field => $value) { if (substr($field, 0, strlen($source)) == $source) { $field = str_replace($source, $pane, $field); $input['panes'][$pane][$field] = $value; $order->{$field} = $value; } } } if ($element['#name'] == "panes[{$pane}][select_address]") { $address = $addresses[$element['#value']]; foreach ($address as $field => $value) { $input['panes'][$pane][$pane . '_' . $field] = $value; $order->{$pane . '_' . $field} = $value; } } $form_state->setUserInput($input); // Forget any previous Ajax submissions, as we send new default values. $form_state->unsetValue('uc_address'); } return $contents; }
/** * Form element submit handler for mollom_test_form(). */ function fieldSubmitForm(array &$form, FormStateInterface $form_state) { // Remove all empty values of the multiple value field. $form_state->setValue('field', array_filter($form_state->getValue('field'))); // Update the storage with submitted values. $storage_record = $form_state->getValues(); // Store the new value and clear out the 'new' field. $new_field = $form_state->getValue(array('field', 'new'), ''); if (!empty($new_field)) { $storage_record['field'][] = $form_state->getValue(array('field', 'new')); $form_state->setValue(array('field', 'new'), ''); $storage_record['field']['new'] = ''; unset($storage_record['field']['add']); $input = $form_state->getUserInput(); $input['field']['new'] = ''; $form_state->setUserInput($input); } $form_state->set('mollom_test', $storage_record); $form_state->setRebuild(TRUE); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { if ($form_state->isRebuilding()) { $form_state->setUserInput(array()); } // Initialize $storage = $form_state->getStorage(); if (empty($storage)) { $user_input = $form_state->getUserInput(); if (empty($user_input)) { $_SESSION['constructions'] = 0; } // Put the initial thing into the storage $storage = ['thing' => ['title' => 'none', 'value' => '']]; $form_state->setStorage($storage); } // Count how often the form is constructed. $_SESSION['constructions']++; drupal_set_message("Form constructions: " . $_SESSION['constructions']); $form['title'] = array('#type' => 'textfield', '#title' => 'Title', '#default_value' => $storage['thing']['title'], '#required' => TRUE); $form['value'] = array('#type' => 'textfield', '#title' => 'Value', '#default_value' => $storage['thing']['value'], '#element_validate' => array('::elementValidateValueCached')); $form['continue_button'] = array('#type' => 'button', '#value' => 'Reset'); $form['continue_submit'] = array('#type' => 'submit', '#value' => 'Continue submit', '#submit' => array('::continueSubmitForm')); $form['submit'] = array('#type' => 'submit', '#value' => 'Save'); // @todo Remove this in https://www.drupal.org/node/2524408, because form // cache immutability is no longer necessary, because we no longer cache // forms during safe HTTP methods. In the meantime, because // Drupal\system\Tests\Form still has test coverage for a poisoned form // cache following a GET request, trick $form_state into caching the form // to keep that test working until we either remove it or change it in // that issue. if ($this->getRequest()->get('immutable')) { $form_state->addBuildInfo('immutable', TRUE); if ($this->getRequest()->get('cache') && $this->getRequest()->isMethodSafe()) { $form_state->setRequestMethod('FAKE'); $form_state->setCached(); } } return $form; }
/** * {@inheritdoc} */ public function prepare(OrderInterface $order, array $form, FormStateInterface $form_state) { // If a quote was explicitly selected, add it to the order. if (isset($form['panes']['quotes']['quotes']['quote_option']['#value']) && isset($form['panes']['quotes']['quotes']['quote_option']['#default_value']) && $form['panes']['quotes']['quotes']['quote_option']['#value'] !== $form['panes']['quotes']['quotes']['quote_option']['#default_value']) { $quote_option = explode('---', $form_state->getValue(['panes', 'quotes', 'quotes', 'quote_option'])); $order->quote['method'] = $quote_option[0]; $order->quote['accessorials'] = $quote_option[1]; $order->data->uc_quote_selected = TRUE; } // If the current quote was never explicitly selected, discard it and // use the default. if (empty($order->data->uc_quote_selected)) { unset($order->quote); } // Ensure that the form builder uses the default value to decide which // radio button should be selected. $input = $form_state->getUserInput(); unset($input['panes']['quotes']['quotes']['quote_option']); $form_state->setUserInput($input); $order->quote_form = uc_quote_build_quote_form($order, !$form_state->get('quote_requested')); $default_option = _uc_quote_extract_default_option($order->quote_form); if ($default_option) { $order->quote['rate'] = $order->quote_form[$default_option]['rate']['#value']; $quote_option = explode('---', $default_option); $order->quote['method'] = $quote_option[0]; $order->quote['accessorials'] = $quote_option[1]; $methods = uc_quote_methods(); $method = $methods[$quote_option[0]]; $label = $method['quote']['accessorials'][$quote_option[1]]; $result = db_query("SELECT line_item_id FROM {uc_order_line_items} WHERE order_id = :id AND type = :type", [':id' => $order->id(), ':type' => 'shipping']); if ($lid = $result->fetchField()) { uc_order_update_line_item($lid, $label, $order->quote['rate']); } else { uc_order_line_item_add($order->id(), 'shipping', $label, $order->quote['rate']); } } else { unset($order->quote); } }
protected function valueForm(&$form, FormStateInterface $form_state) { $values = array(); if ($this->value) { $result = entity_load_multiple_by_properties('user', array('uid' => $this->value)); foreach ($result as $account) { if ($account->id()) { $values[] = $account->getUsername(); } else { $values[] = 'Anonymous'; // Intentionally NOT translated. } } } sort($values); $default_value = implode(', ', $values); $form['value'] = array('#type' => 'textfield', '#title' => $this->t('Usernames'), '#description' => $this->t('Enter a comma separated list of user names.'), '#default_value' => $default_value, '#autocomplete_route_name' => 'user.autocomplete_anonymous'); $user_input = $form_state->getUserInput(); if ($form_state->get('exposed') && !isset($user_input[$this->options['expose']['identifier']])) { $user_input[$this->options['expose']['identifier']] = $default_value; $form_state->setUserInput($user_input); } }
/** * Build a form containing a group of operator | values to apply as a * single filter. */ public function groupForm(&$form, FormStateInterface $form_state) { if (!empty($this->options['group_info']['optional']) && !$this->multipleExposedInput()) { $groups = array('All' => $this->t('- Any -')); } foreach ($this->options['group_info']['group_items'] as $id => $group) { if (!empty($group['title'])) { $groups[$id] = $id != 'All' ? $this->t($group['title']) : $group['title']; } } if (count($groups)) { $value = $this->options['group_info']['identifier']; $form[$value] = array('#title' => $this->options['group_info']['label'], '#type' => $this->options['group_info']['widget'], '#default_value' => $this->group_info, '#options' => $groups); if (!empty($this->options['group_info']['multiple'])) { if (count($groups) < 5) { $form[$value]['#type'] = 'checkboxes'; } else { $form[$value]['#type'] = 'select'; $form[$value]['#size'] = 5; $form[$value]['#multiple'] = TRUE; } unset($form[$value]['#default_value']); $user_input = $form_state->getUserInput(); if (empty($user_input)) { $user_input[$value] = $this->group_info; $form_state->setUserInput($user_input); } } $this->options['expose']['label'] = ''; } }
/** * Alters the view exposed form. * * @param $form * The form build array. Passed by reference. * @param $form_state * The form state. Passed by reference. */ public function exposedFormAlter(&$form, FormStateInterface $form_state) { if (!empty($this->options['submit_button'])) { $form['actions']['submit']['#value'] = $this->options['submit_button']; } // Check if there is exposed sorts for this view $exposed_sorts = array(); foreach ($this->view->sort as $id => $handler) { if ($handler->canExpose() && $handler->isExposed()) { $exposed_sorts[$id] = Html::escape($handler->options['expose']['label']); } } if (count($exposed_sorts)) { $form['sort_by'] = array('#type' => 'select', '#options' => $exposed_sorts, '#title' => $this->options['exposed_sorts_label']); $sort_order = array('ASC' => $this->options['sort_asc_label'], 'DESC' => $this->options['sort_desc_label']); $user_input = $form_state->getUserInput(); if (isset($user_input['sort_by']) && isset($this->view->sort[$user_input['sort_by']])) { $default_sort_order = $this->view->sort[$user_input['sort_by']]->options['order']; } else { $first_sort = reset($this->view->sort); $default_sort_order = $first_sort->options['order']; } if (!isset($user_input['sort_by'])) { $keys = array_keys($exposed_sorts); $user_input['sort_by'] = array_shift($keys); $form_state->setUserInput($user_input); } if ($this->options['expose_sort_order']) { $form['sort_order'] = array('#type' => 'select', '#options' => $sort_order, '#title' => $this->t('Order', array(), array('context' => 'Sort order')), '#default_value' => $default_sort_order); } $form['submit']['#weight'] = 10; } if (!empty($this->options['reset_button'])) { $form['actions']['reset'] = array('#value' => $this->options['reset_button_label'], '#type' => 'submit', '#weight' => 10); // Get an array of exposed filters, keyed by identifier option. $exposed_filters = []; foreach ($this->view->filter as $id => $handler) { if ($handler->canExpose() && $handler->isExposed() && !empty($handler->options['expose']['identifier'])) { $exposed_filters[$handler->options['expose']['identifier']] = $id; } } $all_exposed = array_merge($exposed_sorts, $exposed_filters); // Set the access to FALSE if there is no exposed input. if (!array_intersect_key($all_exposed, $this->view->getExposedInput())) { $form['actions']['reset']['#access'] = FALSE; } } $pager = $this->view->display_handler->getPlugin('pager'); if ($pager) { $pager->exposedFormAlter($form, $form_state); $form_state->set('pager_plugin', $pager); } }
/** * Simulates a form submission within a request, bypassing submitForm(). * * Calling submitForm() will reset the form builder, if two forms were on the * same page, they will be submitted simultaneously. * * @param string $form_id * The unique string identifying the form. * @param \Drupal\Core\Form\FormInterface $form_arg * The form object. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * @param bool $programmed * Whether $form_state->setProgrammed() should be passed TRUE or not. If it * is not set to TRUE, you must provide additional data in $form_state for * the submission to take place. * * @return array * The built form. */ protected function simulateFormSubmission($form_id, FormInterface $form_arg, FormStateInterface $form_state, $programmed = TRUE) { $input = $form_state->getUserInput(); $input['op'] = 'Submit'; $form_state->setUserInput($input)->setProgrammed($programmed)->setSubmitted(); return $this->formBuilder->buildForm($form_arg, $form_state); }
/** * {@inheritdoc} */ public function processForm($form_id, &$form, FormStateInterface &$form_state) { $form_state->setValues([]); // With GET, these forms are always submitted if requested. if ($form_state->isMethodType('get') && $form_state->getAlwaysProcess()) { $input = $form_state->getUserInput(); if (!isset($input['form_build_id'])) { $input['form_build_id'] = $form['#build_id']; } if (!isset($input['form_id'])) { $input['form_id'] = $form_id; } if (!isset($input['form_token']) && isset($form['#token'])) { $input['form_token'] = $this->csrfToken->get($form['#token']); } $form_state->setUserInput($input); } // self::doBuildForm() finishes building the form by calling element // #process functions and mapping user input, if any, to #value properties, // and also storing the values in $form_state->getValues(). We need to // retain the unprocessed $form in case it needs to be cached. $unprocessed_form = $form; $form = $this->doBuildForm($form_id, $form, $form_state); // Only process the input if we have a correct form submission. if ($form_state->isProcessingInput()) { // Form values for programmed form submissions typically do not include a // value for the submit button. But without a triggering element, a // potentially existing #limit_validation_errors property on the primary // submit button is not taken account. Therefore, check whether there is // exactly one submit button in the form, and if so, automatically use it // as triggering_element. $buttons = $form_state->getButtons(); if ($form_state->isProgrammed() && !$form_state->getTriggeringElement() && count($buttons) == 1) { $form_state->setTriggeringElement(reset($buttons)); } $this->formValidator->validateForm($form_id, $form, $form_state); // \Drupal\Component\Utility\Html::getUniqueId() maintains a cache of // element IDs it has seen, so it can prevent duplicates. We want to be // sure we reset that cache when a form is processed, so scenarios that // result in the form being built behind the scenes and again for the // browser don't increment all the element IDs needlessly. if (!FormState::hasAnyErrors()) { // In case of errors, do not break HTML IDs of other forms. Html::resetSeenIds(); } // If there are no errors and the form is not rebuilding, submit the form. if (!$form_state->isRebuilding() && !FormState::hasAnyErrors()) { $submit_response = $this->formSubmitter->doSubmitForm($form, $form_state); // If this form was cached, delete it from the cache after submission. if ($form_state->isCached()) { $this->deleteCache($form['#build_id']); } // If the form submission directly returned a response, return it now. if ($submit_response) { return $submit_response; } } // Don't rebuild or cache form submissions invoked via self::submitForm(). if ($form_state->isProgrammed()) { return; } // If $form_state->isRebuilding() has been set and input has been // processed without validation errors, we are in a multi-step workflow // that is not yet complete. A new $form needs to be constructed based on // the changes made to $form_state during this request. Normally, a submit // handler sets $form_state->isRebuilding() if a fully executed form // requires another step. However, for forms that have not been fully // executed (e.g., Ajax submissions triggered by non-buttons), there is no // submit handler to set $form_state->isRebuilding(). It would not make // sense to redisplay the identical form without an error for the user to // correct, so we also rebuild error-free non-executed forms, regardless // of $form_state->isRebuilding(). // @todo Simplify this logic; considering Ajax and non-HTML front-ends, // along with element-level #submit properties, it makes no sense to // have divergent form execution based on whether the triggering element // has #executes_submit_callback set to TRUE. if (($form_state->isRebuilding() || !$form_state->isExecuted()) && !FormState::hasAnyErrors()) { // Form building functions (e.g., self::handleInputElement()) may use // $form_state->isRebuilding() to determine if they are running in the // context of a rebuild, so ensure it is set. $form_state->setRebuild(); $form = $this->rebuildForm($form_id, $form_state, $form); } } // After processing the form, the form builder or a #process callback may // have called $form_state->setCached() to indicate that the form and form // state shall be cached. But the form may only be cached if // $form_state->disableCache() is not called. Only cache $form as it was // prior to self::doBuildForm(), because self::doBuildForm() must run for // each request to accommodate new user input. Rebuilt forms are not cached // here, because self::rebuildForm() already takes care of that. if (!$form_state->isRebuilding() && $form_state->isCached()) { $this->setCache($form['#build_id'], $unprocessed_form, $form_state); } }
/** * Provide a simple textfield for equality */ protected function valueForm(&$form, FormStateInterface $form_state) { // We have to make some choices when creating this as an exposed // filter form. For example, if the operator is locked and thus // not rendered, we can't render dependencies; instead we only // render the form items we need. $which = 'all'; if (!empty($form['operator'])) { $source = ':input[name="options[operator]"]'; } if ($exposed = $form_state->get('exposed')) { $identifier = $this->options['expose']['identifier']; if (empty($this->options['expose']['use_operator']) || empty($this->options['expose']['operator_id'])) { // exposed and locked. $which = in_array($this->operator, $this->operatorValues(1)) ? 'value' : 'none'; } else { $source = ':input[name="' . $this->options['expose']['operator_id'] . '"]'; } } if ($which == 'all' || $which == 'value') { $form['value'] = array('#type' => 'textfield', '#title' => $this->t('Value'), '#size' => 30, '#default_value' => $this->value); $user_input = $form_state->getUserInput(); if ($exposed && !isset($user_input[$identifier])) { $user_input[$identifier] = $this->value; $form_state->setUserInput($user_input); } if ($which == 'all') { // Setup #states for all operators with one value. foreach ($this->operatorValues(1) as $operator) { $form['value']['#states']['visible'][] = array($source => array('value' => $operator)); } } } if (!isset($form['value'])) { // Ensure there is something in the 'value'. $form['value'] = array('#type' => 'value', '#value' => NULL); } }
protected function valueForm(&$form, FormStateInterface $form_state) { if (empty($this->valueOptions)) { // Initialize the array of possible values for this filter. $this->getValueOptions(); } if ($exposed = $form_state->get('exposed')) { // Exposed filter: use a select box to save space. $filter_form_type = 'select'; } else { // Configuring a filter: use radios for clarity. $filter_form_type = 'radios'; } $form['value'] = array('#type' => $filter_form_type, '#title' => $this->value_value, '#options' => $this->valueOptions, '#default_value' => $this->value); if (!empty($this->options['exposed'])) { $identifier = $this->options['expose']['identifier']; $user_input = $form_state->getUserInput(); if ($exposed && !isset($user_input[$identifier])) { $user_input[$identifier] = $this->value; $form_state->setUserInput($user_input); } // If we're configuring an exposed filter, add an - Any - option. if (!$exposed || empty($this->options['expose']['required'])) { $form['value']['#options'] = array('All' => $this->t('- Any -')) + $form['value']['#options']; } } }
/** * Updates remote languages mappings. * * @param array $form * An associative array containing the initial structure of the form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the complete form. */ public static function updateRemoteLanguagesMappings(array $form, FormStateInterface $form_state) { if (!empty($form_state->getUserInput()['remote_languages_mappings'])) { // The user input containing remote languages mappings from an old // translator, so We have to remove them from here. $user_input = $form_state->getUserInput(); unset($user_input['remote_languages_mappings']); $form_state->setUserInput($user_input); } $form_state->setRebuild(); }
protected function valueForm(&$form, FormStateInterface $form_state) { $form['value'] = array(); $options = array(); $exposed = $form_state->get('exposed'); if (!$exposed) { // Add a select all option to the value form. $options = array('all' => $this->t('Select all')); } $this->getValueOptions(); $options += $this->valueOptions; $default_value = (array) $this->value; $which = 'all'; if (!empty($form['operator'])) { $source = ':input[name="options[operator]"]'; } if ($exposed) { $identifier = $this->options['expose']['identifier']; if (empty($this->options['expose']['use_operator']) || empty($this->options['expose']['operator_id'])) { // exposed and locked. $which = in_array($this->operator, $this->operatorValues(1)) ? 'value' : 'none'; } else { $source = ':input[name="' . $this->options['expose']['operator_id'] . '"]'; } if (!empty($this->options['expose']['reduce'])) { $options = $this->reduceValueOptions(); if (!empty($this->options['expose']['multiple']) && empty($this->options['expose']['required'])) { $default_value = array(); } } if (empty($this->options['expose']['multiple'])) { if (empty($this->options['expose']['required']) && (empty($default_value) || !empty($this->options['expose']['reduce']))) { $default_value = 'All'; } elseif (empty($default_value)) { $keys = array_keys($options); $default_value = array_shift($keys); } else { $copy = $default_value; $default_value = array_shift($copy); } } } if ($which == 'all' || $which == 'value') { $form['value'] = array('#type' => $this->valueFormType, '#title' => $this->valueTitle, '#options' => $options, '#default_value' => $default_value, '#multiple' => TRUE, '#size' => count($options) > 8 ? 8 : count($options)); $user_input = $form_state->getUserInput(); if ($exposed && !isset($user_input[$identifier])) { $user_input[$identifier] = $default_value; $form_state->setUserInput($user_input); } if ($which == 'all') { if (!$exposed && in_array($this->valueFormType, ['checkbox', 'checkboxes', 'radios', 'select'])) { $form['value']['#prefix'] = '<div id="edit-options-value-wrapper">'; $form['value']['#suffix'] = '</div>'; } // Setup #states for all operators with one value. foreach ($this->operatorValues(1) as $operator) { $form['value']['#states']['visible'][] = array($source => array('value' => $operator)); } } } }
/** * Submit callback for the 'reverse', 'shuffle' and 'clear' actions. */ public static function submitAction(array &$form, FormStateInterface $form_state) { $trigger = $form_state->getTriggeringElement(); $op = $trigger['#op']; // Check if we have a form element for the 'items' field. $path = array_merge($form['#parents'], ['items']); $key_exists = NULL; NestedArray::getValue($form_state->getValues(), $path, $key_exists); if ($key_exists) { // Remove any user input for the 'items' element in order to allow the // values set below to be applied. $user_input = $form_state->getUserInput(); NestedArray::setValue($user_input, $path, NULL); $form_state->setUserInput($user_input); $entity = $form_state->getFormObject()->getEntity(); $items_widget = $form_state->getFormObject()->getFormDisplay($form_state)->getRenderer('items'); $subqueue_items = $entity->get('items'); $items_widget->extractFormValues($subqueue_items, $form, $form_state); $items_values = $subqueue_items->getValue(); switch ($op) { case 'reverse': $subqueue_items->setValue(array_reverse($items_values)); break; case 'shuffle': shuffle($items_values); $subqueue_items->setValue($items_values); break; case 'clear': $subqueue_items->setValue(NULL); break; } $form_state->getFormObject()->setEntity($entity); $form_state->setRebuild(); } }
/** * Load the values from the bundle into the user input. * Used during Ajax callback since updating #default_values is ignored. * @param $bundle_name * @param \Drupal\Core\Form\FormStateInterface $form_state */ protected function loadBundleValues($bundle_name, FormStateInterface &$form_state, $current_bundle, $enabled_methods, $methods_weight) { $input = $form_state->getUserInput(); if ($bundle_name == self::NEW_BUNDLE_SELECT_VALUE) { $input['bundle']['name'] = ''; $input['bundle']['machine_name'] = ''; $input['bundle']['description'] = ''; $input['bundle']['is_profile'] = NULL; $input['bundle']['profile_name'] = ''; } else { $input['bundle']['name'] = $current_bundle->getName(); $input['bundle']['machine_name'] = $current_bundle->getMachineName(); $input['bundle']['description'] = $current_bundle->getDescription(); $input['bundle']['is_profile'] = $current_bundle->isProfile() ? 1 : null; $input['bundle']['profile_name'] = $current_bundle->isProfile() ? $current_bundle->getProfileName() : ''; } foreach ($methods_weight as $method_id => $weight) { $enabled = isset($enabled_methods[$method_id]); $input['weight'][$method_id] = $weight; $input['enabled'][$method_id] = $enabled ? 1 : null; } $form_state->setUserInput($input); }
/** * @covers ::setUserInput */ public function testSetUserInput() { $user_input = ['FOO' => 'BAR']; $this->decoratedFormState->setUserInput($user_input)->shouldBeCalled(); $this->assertSame($this->formStateDecoratorBase, $this->formStateDecoratorBase->setUserInput($user_input)); }
/** * {@inheritdoc} */ public function setUserInput(array $user_input) { $this->decoratedFormState->setUserInput($user_input); return $this; }
/** * Provide a simple textfield for equality */ protected function valueForm(&$form, FormStateInterface $form_state) { $form['value']['#tree'] = TRUE; // We have to make some choices when creating this as an exposed // filter form. For example, if the operator is locked and thus // not rendered, we can't render dependencies; instead we only // render the form items we need. $which = 'all'; if (!empty($form['operator'])) { $source = ':input[name="options[operator]"]'; } if ($exposed = $form_state->get('exposed')) { $identifier = $this->options['expose']['identifier']; if (empty($this->options['expose']['use_operator']) || empty($this->options['expose']['operator_id'])) { // exposed and locked. $which = in_array($this->operator, $this->operatorValues(2)) ? 'minmax' : 'value'; } else { $source = ':input[name="' . $this->options['expose']['operator_id'] . '"]'; } } $user_input = $form_state->getUserInput(); if ($which == 'all') { $form['value']['value'] = array('#type' => 'textfield', '#title' => !$exposed ? $this->t('Value') : '', '#size' => 30, '#default_value' => $this->value['value']); // Setup #states for all operators with one value. foreach ($this->operatorValues(1) as $operator) { $form['value']['value']['#states']['visible'][] = array($source => array('value' => $operator)); } if ($exposed && !isset($user_input[$identifier]['value'])) { $user_input[$identifier]['value'] = $this->value['value']; $form_state->setUserInput($user_input); } } elseif ($which == 'value') { // When exposed we drop the value-value and just do value if // the operator is locked. $form['value'] = array('#type' => 'textfield', '#title' => !$exposed ? $this->t('Value') : '', '#size' => 30, '#default_value' => $this->value['value']); if ($exposed && !isset($user_input[$identifier])) { $user_input[$identifier] = $this->value['value']; $form_state->setUserInput($user_input); } } if ($which == 'all' || $which == 'minmax') { $form['value']['min'] = array('#type' => 'textfield', '#title' => !$exposed ? $this->t('Min') : $this->exposedInfo()['label'], '#size' => 30, '#default_value' => $this->value['min'], '#description' => !$exposed ? '' : $this->exposedInfo()['description']); $form['value']['max'] = array('#type' => 'textfield', '#title' => !$exposed ? $this->t('And max') : $this->t('And'), '#size' => 30, '#default_value' => $this->value['max']); if ($which == 'all') { $states = array(); // Setup #states for all operators with two values. foreach ($this->operatorValues(2) as $operator) { $states['#states']['visible'][] = array($source => array('value' => $operator)); } $form['value']['min'] += $states; $form['value']['max'] += $states; } if ($exposed && !isset($user_input[$identifier]['min'])) { $user_input[$identifier]['min'] = $this->value['min']; } if ($exposed && !isset($user_input[$identifier]['max'])) { $user_input[$identifier]['max'] = $this->value['max']; } if (!isset($form['value'])) { // Ensure there is something in the 'value'. $form['value'] = array('#type' => 'value', '#value' => NULL); } } }
protected function valueForm(&$form, FormStateInterface $form_state) { $vocabulary = $this->vocabularyStorage->load($this->options['vid']); if (empty($vocabulary) && $this->options['limit']) { $form['markup'] = array('#markup' => '<div class="form-item">' . $this->t('An invalid vocabulary is selected. Please change it in the options.') . '</div>'); return; } if ($this->options['type'] == 'textfield') { $terms = $this->value ? Term::loadMultiple($this->value) : array(); $form['value'] = array('#title' => $this->options['limit'] ? $this->t('Select terms from vocabulary @voc', array('@voc' => $vocabulary->label())) : $this->t('Select terms'), '#type' => 'textfield', '#default_value' => EntityAutocomplete::getEntityLabels($terms)); if ($this->options['limit']) { $form['value']['#type'] = 'entity_autocomplete'; $form['value']['#target_type'] = 'taxonomy_term'; $form['value']['#selection_settings']['target_bundles'] = array($vocabulary->id()); $form['value']['#tags'] = TRUE; $form['value']['#process_default_value'] = FALSE; } } else { if (!empty($this->options['hierarchy']) && $this->options['limit']) { $tree = $this->termStorage->loadTree($vocabulary->id(), 0, NULL, TRUE); $options = array(); if ($tree) { foreach ($tree as $term) { $choice = new \stdClass(); $choice->option = array($term->id() => str_repeat('-', $term->depth) . SafeMarkup::checkPlain(\Drupal::entityManager()->getTranslationFromContext($term)->label())); $options[] = $choice; } } } else { $options = array(); $query = \Drupal::entityQuery('taxonomy_term')->sort('weight')->sort('name')->addTag('term_access'); if ($this->options['limit']) { $query->condition('vid', $vocabulary->id()); } $terms = Term::loadMultiple($query->execute()); foreach ($terms as $term) { $options[$term->id()] = SafeMarkup::checkPlain(\Drupal::entityManager()->getTranslationFromContext($term)->label()); } } $default_value = (array) $this->value; if ($exposed = $form_state->get('exposed')) { $identifier = $this->options['expose']['identifier']; if (!empty($this->options['expose']['reduce'])) { $options = $this->reduceValueOptions($options); if (!empty($this->options['expose']['multiple']) && empty($this->options['expose']['required'])) { $default_value = array(); } } if (empty($this->options['expose']['multiple'])) { if (empty($this->options['expose']['required']) && (empty($default_value) || !empty($this->options['expose']['reduce']))) { $default_value = 'All'; } elseif (empty($default_value)) { $keys = array_keys($options); $default_value = array_shift($keys); } elseif ($default_value == array('')) { $default_value = 'All'; } else { $copy = $default_value; $default_value = array_shift($copy); } } } $form['value'] = array('#type' => 'select', '#title' => $this->options['limit'] ? $this->t('Select terms from vocabulary @voc', array('@voc' => $vocabulary->label())) : $this->t('Select terms'), '#multiple' => TRUE, '#options' => $options, '#size' => min(9, count($options)), '#default_value' => $default_value); $user_input = $form_state->getUserInput(); if ($exposed && isset($identifier) && !isset($user_input[$identifier])) { $user_input[$identifier] = $default_value; $form_state->setUserInput($user_input); } } if (!$form_state->get('exposed')) { // Retain the helper option $this->helper->buildOptionsForm($form, $form_state); } }
/** * Provide a simple textfield for equality */ protected function valueForm(&$form, FormStateInterface $form_state) { // We have to make some choices when creating this as an exposed // filter form. For example, if the operator is locked and thus // not rendered, we can't render dependencies; instead we only // render the form items we need. $which = 'all'; if (!empty($form['operator'])) { $source = ':input[name="options[operator]"]'; } if ($exposed = $form_state->get('exposed')) { $identifier = $this->options['expose']['identifier']; if (empty($this->options['expose']['use_operator']) || empty($this->options['expose']['operator_id'])) { // exposed and locked. $which = 'value'; } else { $source = ':input[name="' . $this->options['expose']['operator_id'] . '"]'; } } if ($which == 'all' || $which == 'value') { $html_id = Html::getId('leaflet-widget'); $form['wrapper'] = array('#type' => 'fieldset', '#title' => $this->exposedInfo()['label'], '#attributes' => array('class' => array('fieldgroup'))); $form['wrapper']['leaflet_map']['#markup'] = '<div class="leaflet-widget" id="' . $html_id . '"></div>'; $form['#attached']['library'][] = 'bbox/leaflet'; $form['#attached']['library'][] = 'bbox/views'; $form['#attached']['drupalSettings']['bbox']['widgets'][] = $html_id; $form['wrapper'][$identifier] = array('#type' => 'textfield', '#size' => 30, '#attributes' => array('class' => array('bbox-value')), '#default_value' => $this->value); $user_input = $form_state->getUserInput(); if ($exposed && !isset($user_input[$identifier])) { $user_input[$identifier] = $this->value; $form_state->setUserInput($user_input); } if ($which == 'all') { // Setup #states for all operators with one value. foreach ($this->operatorValues(1) as $operator) { $form['value']['#states']['visible'][] = array($source => array('value' => $operator)); } } } if (!isset($form['value'])) { // Ensure there is something in the 'value'. $form['value'] = array('#type' => 'value', '#value' => NULL); } }