我使用两种方法来测试我的表单:
$form = …->form();
然后设置$form
数组的值(更确切地说这是\Symfony\Component\DomCrawler\Form
对象):
documentation的完整示例:
$form = $crawler->selectButton('submit')->form();
// set some values
$form['name'] = 'Lucas';
$form['form_name[subject]'] = 'Hey there!';
// submit the form
$crawler = $client->submit($form);
POST
数据:以前的代码不适用于forms which manage collections(依赖于Javascript创建的字段),因为如果该字段不存在则会引发错误。这就是为什么我也使用this other way。
documentation的完整示例:
// Directly submit a form (but using the Crawler is easier!)
$client->request('POST', '/submit', array('name' => 'Fabien'));
这个解决方案是我知道测试使用Javascript添加的字段管理集合的表单的唯一方法(请参阅上面的文档链接)。但是第二种解决方案更难使用,因为:
and
的表单时,这是不切实际的,该集合依赖于使用Javascript动态创建的字段_token
是否可以使用第一种方式的语法来定义现有字段,然后使用第二种语法添加新动态创建的字段?
换句话说,我想有这样的事情:
$form = $crawler->selectButton('submit')->form();
// set some values for the existing fields
$form['name'] = 'Lucas';
$form['form_name[subject]'] = 'Hey there!';
// submit the form with additional data
$crawler = $client->submit($form, array('name' => 'Fabien'));
但是我收到了这个错误:
无法访问的字段“名称”
并且$form->get('name')->setData('Fabien');
会触发相同的错误。
此示例并不完美,因为表单没有集合,但它足以向您显示我的问题。
当我向现有表单添加一些字段时,我正在寻找一种避免此验证的方法。
答案 0 :(得分:0)
这可以通过从submit()
方法调用稍微修改过的代码来完成:
// Get the form.
$form = $crawler->filter('button')->form();
// Merge existing values with new values.
$values = array_merge_recursive(
$form->getPhpValues(),
array(
// New values.
'FORM_NAME' => array(
'COLLECTION_NAME' => array(
array(
'FIELD_NAME_1' => 'a',
'FIELD_NAME_2' => '1',
)
)
)
)
);
// Submit the form with the existing and new values.
$crawler = $this->client->request($form->getMethod(), $form->getUri(), $values,
$form->getPhpFiles());
此示例中包含新闻值的数组对应于您拥有包含这些name
的字段的表单:
<input type="…" name="FORM_NAME[COLLECTION_NAME][A_NUMBER][FIELD_NAME_1]" />
<input type="…" name="FORM_NAME[COLLECTION_NAME][A_NUMBER][FIELD_NAME_2]" />
字段的数量(索引)无关紧要,PHP将合并数组并提交数据,Symfony将在相应的字段中转换此数据。