4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\DomCrawler;
14 use Symfony\Component\DomCrawler\Field\ChoiceFormField;
15 use Symfony\Component\DomCrawler\Field\FormField;
18 * Form represents an HTML form.
20 * @author Fabien Potencier <fabien@symfony.com>
22 class Form extends Link implements \ArrayAccess
30 * @var FormFieldRegistry
40 * @param \DOMElement $node A \DOMElement instance
41 * @param string $currentUri The URI of the page where the form is embedded
42 * @param string $method The method to use for the link (if null, it defaults to the method defined by the form)
43 * @param string $baseHref The URI of the <base> used for relative links, but not for empty action
45 * @throws \LogicException if the node is not a button inside a form tag
47 public function __construct(\DOMElement $node, $currentUri, $method = null, $baseHref = null)
49 parent::__construct($node, $currentUri, $method);
50 $this->baseHref = $baseHref;
56 * Gets the form node associated with this form.
58 * @return \DOMElement A \DOMElement instance
60 public function getFormNode()
66 * Sets the value of the fields.
68 * @param array $values An array of field values
72 public function setValues(array $values)
74 foreach ($values as $name => $value) {
75 $this->fields->set($name, $value);
82 * Gets the field values.
84 * The returned array does not include file fields (@see getFiles).
86 * @return array An array of field values
88 public function getValues()
91 foreach ($this->fields->all() as $name => $field) {
92 if ($field->isDisabled()) {
96 if (!$field instanceof Field\FileFormField && $field->hasValue()) {
97 $values[$name] = $field->getValue();
105 * Gets the file field values.
107 * @return array An array of file field values
109 public function getFiles()
111 if (!\in_array($this->getMethod(), array('POST', 'PUT', 'DELETE', 'PATCH'))) {
117 foreach ($this->fields->all() as $name => $field) {
118 if ($field->isDisabled()) {
122 if ($field instanceof Field\FileFormField) {
123 $files[$name] = $field->getValue();
131 * Gets the field values as PHP.
133 * This method converts fields with the array notation
134 * (like foo[bar] to arrays) like PHP does.
136 * @return array An array of field values
138 public function getPhpValues()
141 foreach ($this->getValues() as $name => $value) {
142 $qs = http_build_query(array($name => $value), '', '&');
144 parse_str($qs, $expandedValue);
145 $varName = substr($name, 0, \strlen(key($expandedValue)));
146 $values = array_replace_recursive($values, array($varName => current($expandedValue)));
154 * Gets the file field values as PHP.
156 * This method converts fields with the array notation
157 * (like foo[bar] to arrays) like PHP does.
158 * The returned array is consistent with the array for field values
159 * (@see getPhpValues), rather than uploaded files found in $_FILES.
160 * For a compound file field foo[bar] it will create foo[bar][name],
161 * instead of foo[name][bar] which would be found in $_FILES.
163 * @return array An array of file field values
165 public function getPhpFiles()
168 foreach ($this->getFiles() as $name => $value) {
169 $qs = http_build_query(array($name => $value), '', '&');
171 parse_str($qs, $expandedValue);
172 $varName = substr($name, 0, \strlen(key($expandedValue)));
174 array_walk_recursive(
176 function (&$value, $key) {
177 if (ctype_digit($value) && ('size' === $key || 'error' === $key)) {
178 $value = (int) $value;
183 reset($expandedValue);
185 $values = array_replace_recursive($values, array($varName => current($expandedValue)));
193 * Gets the URI of the form.
195 * The returned URI is not the same as the form "action" attribute.
196 * This method merges the value if the method is GET to mimics
199 * @return string The URI
201 public function getUri()
203 $uri = parent::getUri();
205 if (!\in_array($this->getMethod(), array('POST', 'PUT', 'DELETE', 'PATCH'))) {
206 $query = parse_url($uri, PHP_URL_QUERY);
207 $currentParameters = array();
209 parse_str($query, $currentParameters);
212 $queryString = http_build_query(array_merge($currentParameters, $this->getValues()), '', '&');
214 $pos = strpos($uri, '?');
215 $base = false === $pos ? $uri : substr($uri, 0, $pos);
216 $uri = rtrim($base.'?'.$queryString, '?');
222 protected function getRawUri()
224 // If the form was created from a button rather than the form node, check for HTML5 action overrides
225 if ($this->button !== $this->node && $this->button->getAttribute('formaction')) {
226 return $this->button->getAttribute('formaction');
229 return $this->node->getAttribute('action');
233 * Gets the form method.
235 * If no method is defined in the form, GET is returned.
237 * @return string The method
239 public function getMethod()
241 if (null !== $this->method) {
242 return $this->method;
245 // If the form was created from a button rather than the form node, check for HTML5 method override
246 if ($this->button !== $this->node && $this->button->getAttribute('formmethod')) {
247 return strtoupper($this->button->getAttribute('formmethod'));
250 return $this->node->getAttribute('method') ? strtoupper($this->node->getAttribute('method')) : 'GET';
254 * Returns true if the named field exists.
256 * @param string $name The field name
258 * @return bool true if the field exists, false otherwise
260 public function has($name)
262 return $this->fields->has($name);
266 * Removes a field from the form.
268 * @param string $name The field name
270 public function remove($name)
272 $this->fields->remove($name);
276 * Gets a named field.
278 * @param string $name The field name
280 * @return FormField The field instance
282 * @throws \InvalidArgumentException When field is not present in this form
284 public function get($name)
286 return $this->fields->get($name);
290 * Sets a named field.
292 public function set(FormField $field)
294 $this->fields->add($field);
300 * @return FormField[]
302 public function all()
304 return $this->fields->all();
308 * Returns true if the named field exists.
310 * @param string $name The field name
312 * @return bool true if the field exists, false otherwise
314 public function offsetExists($name)
316 return $this->has($name);
320 * Gets the value of a field.
322 * @param string $name The field name
324 * @return FormField The associated Field instance
326 * @throws \InvalidArgumentException if the field does not exist
328 public function offsetGet($name)
330 return $this->fields->get($name);
334 * Sets the value of a field.
336 * @param string $name The field name
337 * @param string|array $value The value of the field
339 * @throws \InvalidArgumentException if the field does not exist
341 public function offsetSet($name, $value)
343 $this->fields->set($name, $value);
347 * Removes a field from the form.
349 * @param string $name The field name
351 public function offsetUnset($name)
353 $this->fields->remove($name);
357 * Disables validation.
361 public function disableValidation()
363 foreach ($this->fields->all() as $field) {
364 if ($field instanceof Field\ChoiceFormField) {
365 $field->disableValidation();
373 * Sets the node for the form.
375 * Expects a 'submit' button \DOMElement and finds the corresponding form element, or the form element itself.
377 * @throws \LogicException If given node is not a button or input or does not have a form ancestor
379 protected function setNode(\DOMElement $node)
381 $this->button = $node;
382 if ('button' === $node->nodeName || ('input' === $node->nodeName && \in_array(strtolower($node->getAttribute('type')), array('submit', 'button', 'image')))) {
383 if ($node->hasAttribute('form')) {
384 // if the node has the HTML5-compliant 'form' attribute, use it
385 $formId = $node->getAttribute('form');
386 $form = $node->ownerDocument->getElementById($formId);
387 if (null === $form) {
388 throw new \LogicException(sprintf('The selected node has an invalid form attribute (%s).', $formId));
394 // we loop until we find a form ancestor
396 if (null === $node = $node->parentNode) {
397 throw new \LogicException('The selected node does not have a form ancestor.');
399 } while ('form' !== $node->nodeName);
400 } elseif ('form' !== $node->nodeName) {
401 throw new \LogicException(sprintf('Unable to submit on a "%s" tag.', $node->nodeName));
408 * Adds form elements related to this form.
410 * Creates an internal copy of the submitted 'button' element and
411 * the form node or the entire document depending on whether we need
412 * to find non-descendant elements through HTML5 'form' attribute.
414 private function initialize()
416 $this->fields = new FormFieldRegistry();
418 $xpath = new \DOMXPath($this->node->ownerDocument);
420 // add submitted button if it has a valid name
421 if ('form' !== $this->button->nodeName && $this->button->hasAttribute('name') && $this->button->getAttribute('name')) {
422 if ('input' == $this->button->nodeName && 'image' == strtolower($this->button->getAttribute('type'))) {
423 $name = $this->button->getAttribute('name');
424 $this->button->setAttribute('value', '0');
426 // temporarily change the name of the input node for the x coordinate
427 $this->button->setAttribute('name', $name.'.x');
428 $this->set(new Field\InputFormField($this->button));
430 // temporarily change the name of the input node for the y coordinate
431 $this->button->setAttribute('name', $name.'.y');
432 $this->set(new Field\InputFormField($this->button));
434 // restore the original name of the input node
435 $this->button->setAttribute('name', $name);
437 $this->set(new Field\InputFormField($this->button));
441 // find form elements corresponding to the current form
442 if ($this->node->hasAttribute('id')) {
443 // corresponding elements are either descendants or have a matching HTML5 form attribute
444 $formId = Crawler::xpathLiteral($this->node->getAttribute('id'));
446 $fieldNodes = $xpath->query(sprintf('descendant::input[@form=%s] | descendant::button[@form=%1$s] | descendant::textarea[@form=%1$s] | descendant::select[@form=%1$s] | //form[@id=%1$s]//input[not(@form)] | //form[@id=%1$s]//button[not(@form)] | //form[@id=%1$s]//textarea[not(@form)] | //form[@id=%1$s]//select[not(@form)]', $formId));
447 foreach ($fieldNodes as $node) {
448 $this->addField($node);
451 // do the xpath query with $this->node as the context node, to only find descendant elements
452 // however, descendant elements with form attribute are not part of this form
453 $fieldNodes = $xpath->query('descendant::input[not(@form)] | descendant::button[not(@form)] | descendant::textarea[not(@form)] | descendant::select[not(@form)]', $this->node);
454 foreach ($fieldNodes as $node) {
455 $this->addField($node);
459 if ($this->baseHref && '' !== $this->node->getAttribute('action')) {
460 $this->currentUri = $this->baseHref;
464 private function addField(\DOMElement $node)
466 if (!$node->hasAttribute('name') || !$node->getAttribute('name')) {
470 $nodeName = $node->nodeName;
471 if ('select' == $nodeName || 'input' == $nodeName && 'checkbox' == strtolower($node->getAttribute('type'))) {
472 $this->set(new Field\ChoiceFormField($node));
473 } elseif ('input' == $nodeName && 'radio' == strtolower($node->getAttribute('type'))) {
474 // there may be other fields with the same name that are no choice
475 // fields already registered (see https://github.com/symfony/symfony/issues/11689)
476 if ($this->has($node->getAttribute('name')) && $this->get($node->getAttribute('name')) instanceof ChoiceFormField) {
477 $this->get($node->getAttribute('name'))->addChoice($node);
479 $this->set(new Field\ChoiceFormField($node));
481 } elseif ('input' == $nodeName && 'file' == strtolower($node->getAttribute('type'))) {
482 $this->set(new Field\FileFormField($node));
483 } elseif ('input' == $nodeName && !\in_array(strtolower($node->getAttribute('type')), array('submit', 'button', 'image'))) {
484 $this->set(new Field\InputFormField($node));
485 } elseif ('textarea' == $nodeName) {
486 $this->set(new Field\TextareaFormField($node));