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
42 * @param \DOMElement $node A \DOMElement instance
43 * @param string $currentUri The URI of the page where the form is embedded
44 * @param string $method The method to use for the link (if null, it defaults to the method defined by the form)
45 * @param string $baseHref The URI of the <base> used for relative links, but not for empty action
47 * @throws \LogicException if the node is not a button inside a form tag
49 public function __construct(\DOMElement $node, $currentUri, $method = null, $baseHref = null)
51 parent::__construct($node, $currentUri, $method);
52 $this->baseHref = $baseHref;
58 * Gets the form node associated with this form.
60 * @return \DOMElement A \DOMElement instance
62 public function getFormNode()
68 * Sets the value of the fields.
70 * @param array $values An array of field values
74 public function setValues(array $values)
76 foreach ($values as $name => $value) {
77 $this->fields->set($name, $value);
84 * Gets the field values.
86 * The returned array does not include file fields (@see getFiles).
88 * @return array An array of field values
90 public function getValues()
93 foreach ($this->fields->all() as $name => $field) {
94 if ($field->isDisabled()) {
98 if (!$field instanceof Field\FileFormField && $field->hasValue()) {
99 $values[$name] = $field->getValue();
107 * Gets the file field values.
109 * @return array An array of file field values
111 public function getFiles()
113 if (!in_array($this->getMethod(), array('POST', 'PUT', 'DELETE', 'PATCH'))) {
119 foreach ($this->fields->all() as $name => $field) {
120 if ($field->isDisabled()) {
124 if ($field instanceof Field\FileFormField) {
125 $files[$name] = $field->getValue();
133 * Gets the field values as PHP.
135 * This method converts fields with the array notation
136 * (like foo[bar] to arrays) like PHP does.
138 * @return array An array of field values
140 public function getPhpValues()
143 foreach ($this->getValues() as $name => $value) {
144 $qs = http_build_query(array($name => $value), '', '&');
146 parse_str($qs, $expandedValue);
147 $varName = substr($name, 0, strlen(key($expandedValue)));
148 $values = array_replace_recursive($values, array($varName => current($expandedValue)));
156 * Gets the file field values as PHP.
158 * This method converts fields with the array notation
159 * (like foo[bar] to arrays) like PHP does.
160 * The returned array is consistent with the array for field values
161 * (@see getPhpValues), rather than uploaded files found in $_FILES.
162 * For a compound file field foo[bar] it will create foo[bar][name],
163 * instead of foo[name][bar] which would be found in $_FILES.
165 * @return array An array of file field values
167 public function getPhpFiles()
170 foreach ($this->getFiles() as $name => $value) {
171 $qs = http_build_query(array($name => $value), '', '&');
173 parse_str($qs, $expandedValue);
174 $varName = substr($name, 0, strlen(key($expandedValue)));
175 $values = array_replace_recursive($values, array($varName => current($expandedValue)));
183 * Gets the URI of the form.
185 * The returned URI is not the same as the form "action" attribute.
186 * This method merges the value if the method is GET to mimics
189 * @return string The URI
191 public function getUri()
193 $uri = parent::getUri();
195 if (!in_array($this->getMethod(), array('POST', 'PUT', 'DELETE', 'PATCH'))) {
196 $query = parse_url($uri, PHP_URL_QUERY);
197 $currentParameters = array();
199 parse_str($query, $currentParameters);
202 $queryString = http_build_query(array_merge($currentParameters, $this->getValues()), null, '&');
204 $pos = strpos($uri, '?');
205 $base = false === $pos ? $uri : substr($uri, 0, $pos);
206 $uri = rtrim($base.'?'.$queryString, '?');
212 protected function getRawUri()
214 return $this->node->getAttribute('action');
218 * Gets the form method.
220 * If no method is defined in the form, GET is returned.
222 * @return string The method
224 public function getMethod()
226 if (null !== $this->method) {
227 return $this->method;
230 return $this->node->getAttribute('method') ? strtoupper($this->node->getAttribute('method')) : 'GET';
234 * Returns true if the named field exists.
236 * @param string $name The field name
238 * @return bool true if the field exists, false otherwise
240 public function has($name)
242 return $this->fields->has($name);
246 * Removes a field from the form.
248 * @param string $name The field name
250 public function remove($name)
252 $this->fields->remove($name);
256 * Gets a named field.
258 * @param string $name The field name
260 * @return FormField The field instance
262 * @throws \InvalidArgumentException When field is not present in this form
264 public function get($name)
266 return $this->fields->get($name);
270 * Sets a named field.
272 * @param FormField $field The field
274 public function set(FormField $field)
276 $this->fields->add($field);
282 * @return FormField[]
284 public function all()
286 return $this->fields->all();
290 * Returns true if the named field exists.
292 * @param string $name The field name
294 * @return bool true if the field exists, false otherwise
296 public function offsetExists($name)
298 return $this->has($name);
302 * Gets the value of a field.
304 * @param string $name The field name
306 * @return FormField The associated Field instance
308 * @throws \InvalidArgumentException if the field does not exist
310 public function offsetGet($name)
312 return $this->fields->get($name);
316 * Sets the value of a field.
318 * @param string $name The field name
319 * @param string|array $value The value of the field
321 * @throws \InvalidArgumentException if the field does not exist
323 public function offsetSet($name, $value)
325 $this->fields->set($name, $value);
329 * Removes a field from the form.
331 * @param string $name The field name
333 public function offsetUnset($name)
335 $this->fields->remove($name);
339 * Disables validation.
343 public function disableValidation()
345 foreach ($this->fields->all() as $field) {
346 if ($field instanceof Field\ChoiceFormField) {
347 $field->disableValidation();
355 * Sets the node for the form.
357 * Expects a 'submit' button \DOMElement and finds the corresponding form element, or the form element itself.
359 * @param \DOMElement $node A \DOMElement instance
361 * @throws \LogicException If given node is not a button or input or does not have a form ancestor
363 protected function setNode(\DOMElement $node)
365 $this->button = $node;
366 if ('button' === $node->nodeName || ('input' === $node->nodeName && in_array(strtolower($node->getAttribute('type')), array('submit', 'button', 'image')))) {
367 if ($node->hasAttribute('form')) {
368 // if the node has the HTML5-compliant 'form' attribute, use it
369 $formId = $node->getAttribute('form');
370 $form = $node->ownerDocument->getElementById($formId);
371 if (null === $form) {
372 throw new \LogicException(sprintf('The selected node has an invalid form attribute (%s).', $formId));
378 // we loop until we find a form ancestor
380 if (null === $node = $node->parentNode) {
381 throw new \LogicException('The selected node does not have a form ancestor.');
383 } while ('form' !== $node->nodeName);
384 } elseif ('form' !== $node->nodeName) {
385 throw new \LogicException(sprintf('Unable to submit on a "%s" tag.', $node->nodeName));
392 * Adds form elements related to this form.
394 * Creates an internal copy of the submitted 'button' element and
395 * the form node or the entire document depending on whether we need
396 * to find non-descendant elements through HTML5 'form' attribute.
398 private function initialize()
400 $this->fields = new FormFieldRegistry();
402 $xpath = new \DOMXPath($this->node->ownerDocument);
404 // add submitted button if it has a valid name
405 if ('form' !== $this->button->nodeName && $this->button->hasAttribute('name') && $this->button->getAttribute('name')) {
406 if ('input' == $this->button->nodeName && 'image' == strtolower($this->button->getAttribute('type'))) {
407 $name = $this->button->getAttribute('name');
408 $this->button->setAttribute('value', '0');
410 // temporarily change the name of the input node for the x coordinate
411 $this->button->setAttribute('name', $name.'.x');
412 $this->set(new Field\InputFormField($this->button));
414 // temporarily change the name of the input node for the y coordinate
415 $this->button->setAttribute('name', $name.'.y');
416 $this->set(new Field\InputFormField($this->button));
418 // restore the original name of the input node
419 $this->button->setAttribute('name', $name);
421 $this->set(new Field\InputFormField($this->button));
425 // find form elements corresponding to the current form
426 if ($this->node->hasAttribute('id')) {
427 // corresponding elements are either descendants or have a matching HTML5 form attribute
428 $formId = Crawler::xpathLiteral($this->node->getAttribute('id'));
430 $fieldNodes = $xpath->query(sprintf('descendant::input[@form=%s] | descendant::button[@form=%s] | descendant::textarea[@form=%s] | descendant::select[@form=%s] | //form[@id=%s]//input[not(@form)] | //form[@id=%s]//button[not(@form)] | //form[@id=%s]//textarea[not(@form)] | //form[@id=%s]//select[not(@form)]', $formId, $formId, $formId, $formId, $formId, $formId, $formId, $formId));
431 foreach ($fieldNodes as $node) {
432 $this->addField($node);
435 // do the xpath query with $this->node as the context node, to only find descendant elements
436 // however, descendant elements with form attribute are not part of this form
437 $fieldNodes = $xpath->query('descendant::input[not(@form)] | descendant::button[not(@form)] | descendant::textarea[not(@form)] | descendant::select[not(@form)]', $this->node);
438 foreach ($fieldNodes as $node) {
439 $this->addField($node);
443 if ($this->baseHref && '' !== $this->node->getAttribute('action')) {
444 $this->currentUri = $this->baseHref;
448 private function addField(\DOMElement $node)
450 if (!$node->hasAttribute('name') || !$node->getAttribute('name')) {
454 $nodeName = $node->nodeName;
455 if ('select' == $nodeName || 'input' == $nodeName && 'checkbox' == strtolower($node->getAttribute('type'))) {
456 $this->set(new Field\ChoiceFormField($node));
457 } elseif ('input' == $nodeName && 'radio' == strtolower($node->getAttribute('type'))) {
458 // there may be other fields with the same name that are no choice
459 // fields already registered (see https://github.com/symfony/symfony/issues/11689)
460 if ($this->has($node->getAttribute('name')) && $this->get($node->getAttribute('name')) instanceof ChoiceFormField) {
461 $this->get($node->getAttribute('name'))->addChoice($node);
463 $this->set(new Field\ChoiceFormField($node));
465 } elseif ('input' == $nodeName && 'file' == strtolower($node->getAttribute('type'))) {
466 $this->set(new Field\FileFormField($node));
467 } elseif ('input' == $nodeName && !in_array(strtolower($node->getAttribute('type')), array('submit', 'button', 'image'))) {
468 $this->set(new Field\InputFormField($node));
469 } elseif ('textarea' == $nodeName) {
470 $this->set(new Field\TextareaFormField($node));