Symfony\Component\DomCrawler\Field\ChoiceFormField::addChoice PHP Method

addChoice() public method

Adds a choice to the current ones.
public addChoice ( DOMElement $node )
$node DOMElement
    public function addChoice(\DOMElement $node)
    {
        if (!$this->multiple && 'radio' !== $this->type) {
            throw new \LogicException(sprintf('Unable to add a choice for "%s" as it is not multiple or is not a radio button.', $this->name));
        }
        $option = $this->buildOptionValue($node);
        $this->options[] = $option;
        if ($node->hasAttribute('checked')) {
            $this->value = $option['value'];
        }
    }

Usage Example

Example #1
0
 public function testCheckboxes()
 {
     $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name'));
     $field = new ChoiceFormField($node);
     $this->assertFalse($field->hasValue(), '->hasValue() returns false when the checkbox is not checked');
     $this->assertNull($field->getValue(), '->getValue() returns null if the checkbox is not checked');
     $this->assertFalse($field->isMultiple(), '->hasValue() returns false for checkboxes');
     try {
         $field->addChoice(new \DOMNode());
         $this->fail('->addChoice() throws a \\LogicException for checkboxes');
     } catch (\LogicException $e) {
         $this->assertTrue(true, '->initialize() throws a \\LogicException for checkboxes');
     }
     $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name', 'checked' => 'checked'));
     $field = new ChoiceFormField($node);
     $this->assertTrue($field->hasValue(), '->hasValue() returns true when the checkbox is checked');
     $this->assertEquals('1', $field->getValue(), '->getValue() returns 1 if the checkbox is checked and has no value attribute');
     $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name', 'checked' => 'checked', 'value' => 'foo'));
     $field = new ChoiceFormField($node);
     $this->assertEquals('foo', $field->getValue(), '->getValue() returns the value attribute if the checkbox is checked');
     $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name', 'checked' => 'checked', 'value' => 'foo'));
     $field = new ChoiceFormField($node);
     $field->setValue(false);
     $this->assertNull($field->getValue(), '->setValue() unchecks the checkbox is value is false');
     $field->setValue(true);
     $this->assertEquals('foo', $field->getValue(), '->setValue() checks the checkbox is value is true');
     try {
         $field->setValue('bar');
         $this->fail('->setValue() throws an \\InvalidArgumentException if the value is not one from the value attribute');
     } catch (\InvalidArgumentException $e) {
         $this->assertTrue(true, '->setValue() throws an \\InvalidArgumentException if the value is not one from the value attribute');
     }
 }