Christophe Coevoet
Contributed by Christophe Coevoet in #20467

The DomCrawler component eases DOM navigation for HTML and XML documents, making it very useful for functional tests and web scrapers. One of its most popular features allows to fill in and submit forms. But first, you must obtain the object that represents the form via one of its buttons:

1
2
3
4
5
6
7
use Symfony\Component\DomCrawler\Crawler;

$html = '<html> ... </html>';
$crawler = new Crawler($html);

$form = $crawler->selectButton('Save Changes')->form();
// fill in and submit the form...

However, starting from HTML5, buttons of type "submit" can define several attributes to override the original form action, target, method, etc.

1
2
3
4
5
6
7
8
<form action="/save" method="GET">
    <!-- ... -->

    <input type="submit" value="Save Changes"
           formaction="/save-and-close" formmethod="POST">
    <input type="submit" value="Save and Add Another"
           formaction="/save-and-add" formmethod="POST">
</form>

In Symfony 3.3 we added support for the formaction and formmethod attributes. Therefore, you'll always get the right action and method when getting the form via one of its buttons:

1
2
3
4
5
// ...
$form = $crawler->selectButton('Save Changes')->form();
// $form->getUri() -> '/save-and-close'
$form = $crawler->selectButton('Save and Add Another')->form();
// $form->getUri() -> '/save-and-add'
Published in #Living on the edge