setValueForElement example

$input_exists = FALSE;
    $input = NestedArray::getValue($form_state->getValues()$element['#parents']$input_exists);
    if ($input_exists) {

      $title = static::getElementTitle($element$complete_form);
      $date_format = $element['#date_date_element'] != 'none' ? static::getHtml5DateFormat($element) : '';
      $time_format = $element['#date_time_element'] != 'none' ? static::getHtml5TimeFormat($element) : '';
      $format = trim($date_format . ' ' . $time_format);

      // If there's empty input and the field is not required, set it to empty.       if (empty($input['date']) && empty($input['time']) && !$element['#required']) {
        $form_state->setValueForElement($element, NULL);
      }
      // If there's empty input and the field is required, set an error. A       // reminder of the required format in the message provides a good UX.       elseif (empty($input['date']) && empty($input['time']) && $element['#required']) {
        $form_state->setError($elementt('The %field date is required. Please enter a date in the format %format.', ['%field' => $title, '%format' => static::formatExample($format)]));
      }
      else {
        // If the date is valid, set it.         $date = $input['object'];
        if ($date instanceof DrupalDateTime && !$date->hasErrors()) {
          $form_state->setValueForElement($element$date);
        }
if (strlen($pass1) > 0 || strlen($pass2) > 0) {
      if (strcmp($pass1$pass2)) {
        $form_state->setError($elementt('The specified passwords do not match.'));
      }
    }
    elseif ($element['#required'] && $form_state->getUserInput()) {
      $form_state->setError($elementt('Password field is required.'));
    }

    // Password field must be converted from a two-element array into a single     // string regardless of validation results.     $form_state->setValueForElement($element['pass1'], NULL);
    $form_state->setValueForElement($element['pass2'], NULL);
    $form_state->setValueForElement($element$pass1);

    return $element;
  }

}

    ];
    $element['#element_validate'][] = [static::class, 'validateElement'];

    return $element;
  }

  /** * {@inheritdoc} */
  public static function validateElement(array $element, FormStateInterface $form_state) {
    $form_state->setValueForElement($element[$element['state']['#key_column'] => $element['state']['#value']]);
  }

  /** * {@inheritdoc} */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    return is_a($field_definition->getClass(), ModerationStateFieldItemList::class, TRUE);
  }

  /** * {@inheritdoc} */


    // Check required property based on the FID.     if ($element['#required'] && empty($element['fids']['#value']) && !in_array($clicked_button['upload_button', 'remove_button'])) {
      // We expect the field name placeholder value to be wrapped in t()       // here, so it won't be escaped again as it's already marked safe.       $form_state->setError($elementt('@name field is required.', ['@name' => $element['#title']]));
    }

    // Consolidate the array value of this field to array of FIDs.     if (!$element['#extended']) {
      $form_state->setValueForElement($element$element['fids']['#value']);
    }
  }

  /** * Wraps the file usage service. * * @return \Drupal\file\FileUsage\FileUsageInterface */
  protected static function fileUsage() {
    return \Drupal::service('file.usage');
  }

}
/** * {@inheritdoc} */
  public function isValueEmpty($key) {
    return $this->decoratedFormState->isValueEmpty($key);
  }

  /** * {@inheritdoc} */
  public function setValueForElement(array $element$value) {
    $this->decoratedFormState->setValueForElement($element$value);

    return $this;
  }

  /** * {@inheritdoc} */
  public function setResponse(Response $response) {
    $this->decoratedFormState->setResponse($response);

    return $this;
  }
    // 0 == 'any string'.     $index = array_search('_none', $values, TRUE);
    if ($index !== FALSE) {
      unset($values[$index]);
    }

    // Transpose selections from field => delta to delta => field.     $items = [];
    foreach ($values as $value) {
      $items[] = [$element['#key_column'] => $value];
    }
    $form_state->setValueForElement($element$items);
  }

  /** * Returns the array of options for the widget. * * @param \Drupal\Core\Entity\FieldableEntityInterface $entity * The entity for which to return options. * * @return array * The array of options for the widget. */
  
/** * Form element validation handler. * * @param array $element * The allowed_view_modes form element. * @param \Drupal\Core\Form\FormStateInterface $form_state * The form state. */
  public static function validateOptions(array &$element, FormStateInterface $form_state) {
    // Filters the #value property so only selected values appear in the     // config.     $form_state->setValueForElement($elementarray_filter($element['#value']));
  }

  /** * Builds the render array for the given media entity in the given langcode. * * @param \Drupal\media\MediaInterface $media * A media entity to render. * @param string $view_mode * The view mode to render it in. * @param string $langcode * Language code in which the media entity should be rendered. * * @return array * A render array. */

  public static function validateFormElement(array &$element, FormStateInterface $form_state) {
    // Trim the submitted value of whitespace and slashes.     $alias = rtrim(trim($element['alias']['#value']), " \\/");
    if ($alias !== '') {
      $form_state->setValueForElement($element['alias']$alias);

      /** @var \Drupal\path_alias\PathAliasInterface $path_alias */
      $path_alias = \Drupal::entityTypeManager()->getStorage('path_alias')->create([
        'path' => $element['source']['#value'],
        'alias' => $alias,
        'langcode' => $element['langcode']['#value'],
      ]);
      $violations = $path_alias->validate();

      foreach ($violations as $violation) {
        // Newly created entities do not have a system path yet, so we need to

  public function testSetValueForElement() {
    $element = [
      '#parents' => [
        'foo',
        'bar',
      ],
    ];
    $value = $this->randomMachineName();

    $form_state = new FormStateValuesTraitStub();
    $form_state->setValueForElement($element$value);
    $expected = [
      'foo' => [
        'bar' => $value,
      ],
    ];
    $this->assertSame($expected$form_state->getValues());
  }

  /** * @covers ::getValue * * @dataProvider providerGetValue */
$definition = $this->entityTypeManager->getDefinition($this->targetEntityTypeId);
    $form['#title'] = $this->t('Add new @entity-type %label', ['@entity-type' => $definition->getLabel(), '%label' => $this->entityType->getSingularLabel()]);
    return $form;
  }

  /** * {@inheritdoc} */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form$form_state);

    $form_state->setValueForElement($form['id']$this->targetEntityTypeId . '.' . $form_state->getValue('id'));
  }

  /** * {@inheritdoc} */
  protected function prepareEntity() {
    $definition = $this->entityTypeManager->getDefinition($this->targetEntityTypeId);
    if (!$definition->get('field_ui_base_route') || !$definition->hasViewBuilderClass()) {
      throw new NotFoundHttpException();
    }

    
'#theme_wrappers' => ['form_element'],
    ];
  }

  /** * Form element validation handler for #type 'email'. * * Note that #maxlength and #required is validated by _form_validate() already. */
  public static function validateEmail(&$element, FormStateInterface $form_state, &$complete_form) {
    $value = trim($element['#value']);
    $form_state->setValueForElement($element$value);

    if ($value !== '' && !\Drupal::service('email.validator')->isValid($value)) {
      $form_state->setError($elementt('The email address %mail is not valid.', ['%mail' => $value]));
    }
  }

  /** * Prepares a #type 'email' render element for input.html.twig. * * @param array $element * An associative array containing the properties of the element. * Properties used: #title, #value, #description, #size, #maxlength, * #placeholder, #required, #attributes. * * @return array * The $element with prepared variables ready for input.html.twig. */

      }

      // Use only the last value if the form element does not support multiple       // matches (tags).       if (!$element['#tags'] && !empty($value)) {
        $last_value = $value[count($value) - 1];
        $value = $last_value['target_id'] ?? $last_value;
      }
    }

    $form_state->setValueForElement($element$value);
  }

  /** * Finds an entity from an autocomplete input without an explicit ID. * * The method will return an entity ID if one single entity unambiguously * matches the incoming input, and assign form errors otherwise. * * @param \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface $handler * Entity reference selection plugin. * @param string $input * Single string from autocomplete element. * @param array $element * The form element to set a form error. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current form state. * @param bool $strict * Whether to trigger a form error if an element from $input (eg. an entity) * is not found. * * @return int|null * Value of a matching entity ID, or NULL if none. */

  public function submitOptionsForm(&$form, FormStateInterface $form_state) {
    $element = ['#parents' => ['query', 'options', 'query_tags']];
    $value = NestedArray::getValue($form_state->getValues()$element['#parents']);
    // When toggling a display to override defaults or vice-versa the submit     // handler gets invoked twice, and we don't want to bash the values from the     // original call.     if (is_array($value)) {
      return;
    }
    $value = array_filter(array_map('trim', explode(',', $value)));
    $form_state->setValueForElement($element$value);
  }

  /** * Adds a relationship to the query. * * A relationship is an alternative endpoint to a series of table * joins. Relationships must be aliases of the primary table and * they must join either to the primary table or to a pre-existing * relationship. * * An example of a relationship would be a node reference table. * If you have a node reference named 'book_parent' which links to a * parent node, you could set up a relationship 'node_book_parent' * to 'node'. Then, anything that links to 'node' can link to * 'node_book_parent' instead, thus allowing all properties of * both nodes to be available in the query. * * @param $alias * What this relationship will be called, and is also the alias * for the table. * @param \Drupal\views\Plugin\views\join\JoinPluginBase $join * A Join object (or derived object) to join the alias in. * @param $base * The name of the 'base' table this relationship represents; this * tells the join search which path to attempt to use when finding * the path to this relationship. * @param $link_point * If this relationship links to something other than the primary * table, specify that table here. For example, a 'track' node * might have a relationship to an 'album' node, which might * have a relationship to an 'artist' node. */
$buttons[] = $element;
        $form_state->setButtons($buttons);
        if ($this->buttonWasClicked($element$form_state)) {
          $form_state->setTriggeringElement($element);
        }
      }
    }

    // Set the element's value in $form_state->getValues(), but only, if its key     // does not exist yet (a #value_callback may have already populated it).     if (!NestedArray::keyExists($form_state->getValues()$element['#parents'])) {
      $form_state->setValueForElement($element$element['#value']);
    }
  }

  /** * Detects if an element triggered the form submission via Ajax. * * This detects button or non-button controls that trigger a form submission * via Ajax or some other scriptable environment. These environments can set * the special input key '_triggering_element_name' to identify the triggering * element. If the name alone doesn't identify the element uniquely, the input * key '_triggering_element_value' may also be set to require a match on * element value. An example where this is needed is if there are several * // buttons all named 'op', and only differing in their value. */
/** * Render API callback: Processes the allowed formats value. * * Ensure the element's value is an indexed array of selected format IDs. * This function is assigned as an #element_validate callback. * * @see static::fieldSettingsForm() */
  public static function validateAllowedFormats(array &$element, FormStateInterface $form_state) {
    $value = array_values(array_filter($form_state->getValue($element['#parents'])));
    $form_state->setValueForElement($element$value);
  }

  /** * {@inheritdoc} */
  public static function calculateDependencies(FieldDefinitionInterface $field_definition) {
    // Add explicitly allowed formats as config dependencies.     $format_dependencies = [];
    $dependencies = parent::calculateDependencies($field_definition);
    if (!is_null($field_definition->getSetting('allowed_formats'))) {
      $format_dependencies = array_map(function Dstring $format_id) {
        
Home | Imprint | This part of the site doesn't use cookies.