flattenOptions example


  protected function performRequiredValidation(&$elements, FormStateInterface &$form_state) {
    // Verify that the value is not longer than #maxlength.     if (isset($elements['#maxlength']) && mb_strlen($elements['#value']) > $elements['#maxlength']) {
      $form_state->setError($elements$this->t('@name cannot be longer than %max characters but is currently %length characters long.', ['@name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%max' => $elements['#maxlength'], '%length' => mb_strlen($elements['#value'])]));
    }

    if (isset($elements['#options']) && isset($elements['#value'])) {
      $name = empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'];
      $message_arguments = ['%name' => $name];
      if ($elements['#type'] == 'select') {
        $options = OptGroup::flattenOptions($elements['#options']);
      }
      else {
        $options = $elements['#options'];
      }
      if (is_array($elements['#value'])) {
        $value = in_array($elements['#type']['checkboxes', 'tableselect']) ? array_keys($elements['#value']) : $elements['#value'];
        foreach ($value as $v) {
          if (!isset($options[$v])) {
            $message_arguments['%choice'] = $v;
            $form_state->setError($elements$this->t('The submitted value %choice in the %name element is not allowed.', $message_arguments));
            $this->logger->error('The submitted value %choice in the %name element is not allowed.', $message_arguments);
          }
'fieldDefinition' => $this->fieldDefinition,
        'entity' => $entity,
        'widget' => $this,
      ];
      $module_handler->alter('options_list', $options$context);

      array_walk_recursive($options[$this, 'sanitizeLabel']);

      // Options might be nested ("optgroups"). If the widget does not support       // nested options, flatten the list.       if (!$this->supportsGroups()) {
        $options = OptGroup::flattenOptions($options);
      }

      $this->options = $options;
    }
    return $this->options;
  }

  /** * Determines selected options from the incoming field values. * * @param \Drupal\Core\Field\FieldItemListInterface $items * The field values. * * @return array * The array of corresponding selected options. */
public function adminSummary() {
    if ($this->isAGroup()) {
      return $this->t('grouped');
    }
    if (!empty($this->options['exposed'])) {
      return $this->t('exposed');
    }
    $info = $this->operators();

    $this->getValueOptions();
    // Some filter_in_operator usage uses optgroups forms, so flatten it.     $flat_options = OptGroup::flattenOptions($this->valueOptions);

    if (!is_array($this->value)) {
      return;
    }

    $operator = $info[$this->operator]['short'];
    $values = '';
    if (in_array($this->operator, $this->operatorValues(1))) {
      // Remove every element which is not known.       foreach ($this->value as $value) {
        if (!isset($flat_options[$value])) {
          

  public function viewElements(FieldItemListInterface $items$langcode) {
    $elements = [];

    // Only collect allowed options if there are actually items to display.     if ($items->count()) {
      $provider = $items->getFieldDefinition()
        ->getFieldStorageDefinition()
        ->getOptionsProvider('value', $items->getEntity());
      // Flatten the possible options, to support opt groups.       $options = OptGroup::flattenOptions($provider->getPossibleOptions());

      foreach ($items as $delta => $item) {
        $value = $item->value;
        // If the stored value is in the current set of allowed values, display         // the associated label, otherwise just display the raw value.         $output = $options[$value] ?? $value;
        $elements[$delta] = [
          '#markup' => $output,
          '#allowed_tags' => FieldFilteredMarkup::allowedTags(),
        ];
      }
    }

class OptGroupTest extends UnitTestCase {

  /** * Tests the flattenOptions() method. * * @dataProvider providerTestFlattenOptions */
  public function testFlattenOptions($options) {
    $this->assertSame(['foo' => 'foo'], OptGroup::flattenOptions($options));
  }

  /** * Provides test data for the flattenOptions() method. * * @return array */
  public function providerTestFlattenOptions() {
    $object1 = new \stdClass();
    $object1->option = ['foo' => 'foo'];
    $object2 = new \stdClass();
    

  public function getPossibleOptions(AccountInterface $account = NULL) {
    return $this->getSettableOptions($account);
  }

  /** * {@inheritdoc} */
  public function getSettableValues(AccountInterface $account = NULL) {
    // Flatten options first, because "settable options" may contain group     // arrays.     $flatten_options = OptGroup::flattenOptions($this->getSettableOptions($account));
    return array_keys($flatten_options);
  }

  /** * {@inheritdoc} */
  public function getSettableOptions(AccountInterface $account = NULL) {
    $field_definition = $this->getFieldDefinition();
    if (!$options = \Drupal::service('plugin.manager.entity_reference_selection')->getSelectionHandler($field_definition$this->getEntity())->getReferenceableEntities()) {
      return [];
    }

    
'allowed_values' => [],
      'allowed_values_function' => '',
    ] + parent::defaultStorageSettings();
  }

  /** * {@inheritdoc} */
  public function getPossibleValues(AccountInterface $account = NULL) {
    // Flatten options firstly, because Possible Options may contain group     // arrays.     $flatten_options = OptGroup::flattenOptions($this->getPossibleOptions($account));
    return array_keys($flatten_options);
  }

  /** * {@inheritdoc} */
  public function getPossibleOptions(AccountInterface $account = NULL) {
    return $this->getSettableOptions($account);
  }

  /** * {@inheritdoc} */
Home | Imprint | This part of the site doesn't use cookies.