表单测试:如何将集合提交到现有表单?

Form tests: How to submit a collection to an existing form?

我用两种方法来测试我的表格:

通过使用$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 (relying on fields created by Javascript) because it throws an error if the field doesn't exist. That's why I also use this other way

来自 documentation 的完整示例:

// Directly submit a form (but using the Crawler is easier!)
$client->request('POST', '/submit', array('name' => 'Fabien'));

这个解决方案是我所知道的测试表单的唯一方法,这些表单管理由 Javascript 添加的字段的集合(请参阅上面的文档 link)。但是第二种解决方案更难使用,因为:

我的问题

是否可以使用第一种方法中的语法来定义现有字段,然后使用第二种语法添加新的动态创建的字段?

换句话说,我想要这样的东西:

$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'));

但是我得到这个错误:

Unreachable field "name"

$form->get('name')->setData('Fabien');触发相同的错误。

这个例子并不完美,因为表单没有集合,但足以向您展示我的问题。

当我向现有表单添加一些字段时,我正在寻找一种避免此验证的方法。

这可以通过从 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());

本例中包含新闻值的数组对应于一个表单,其中您的字段包含这些 names:

<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会在相应的字段中转换此数据。