Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. ChoiceFormField.php

function ChoiceFormField::initialize

Initializes the form field.

Throws

\LogicException When node type is incorrect

Overrides FormField::initialize

File

vendor/symfony/dom-crawler/Field/ChoiceFormField.php, line 179

Class

ChoiceFormField
ChoiceFormField represents a choice form field.

Namespace

Symfony\Component\DomCrawler\Field

Code

protected function initialize() : void {
    if ('input' !== $this->node->nodeName && 'select' !== $this->node->nodeName) {
        throw new \LogicException(\sprintf('A ChoiceFormField can only be created from an input or select tag (%s given).', $this->node->nodeName));
    }
    if ('input' === $this->node->nodeName && 'checkbox' !== strtolower($this->node
        ->getAttribute('type')) && 'radio' !== strtolower($this->node
        ->getAttribute('type'))) {
        throw new \LogicException(\sprintf('A ChoiceFormField can only be created from an input tag with a type of checkbox or radio (given type is "%s").', $this->node
            ->getAttribute('type')));
    }
    $this->value = null;
    $this->options = [];
    $this->multiple = false;
    if ('input' == $this->node->nodeName) {
        $this->type = strtolower($this->node
            ->getAttribute('type'));
        $optionValue = $this->buildOptionValue($this->node);
        $this->options[] = $optionValue;
        if ($this->node
            ->hasAttribute('checked')) {
            $this->value = $optionValue['value'];
        }
    }
    else {
        $this->type = 'select';
        if ($this->node
            ->hasAttribute('multiple')) {
            $this->multiple = true;
            $this->value = [];
            $this->name = str_replace('[]', '', $this->name);
        }
        $found = false;
        foreach ($this->xpath
            ->query('descendant::option', $this->node) as $option) {
            $optionValue = $this->buildOptionValue($option);
            $this->options[] = $optionValue;
            if ($option->hasAttribute('selected')) {
                $found = true;
                if ($this->multiple) {
                    $this->value[] = $optionValue['value'];
                }
                else {
                    $this->value = $optionValue['value'];
                }
            }
        }
        // if no option is selected and if it is a simple select box, take the first option as the value
        if (!$found && !$this->multiple && $this->options) {
            $this->value = $this->options[0]['value'];
        }
    }
}
RSS feed
Powered by Drupal