首页 文章

表单测试:如何将表单提交到现有表单? [重复]

提问于
浏览
1

这个问题在这里已有答案:

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

使用$ 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创建的字段),因为如果字段没有't exist. That'为什么我也使用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'); 触发相同的错误 .

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

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

1 回答

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

相关问题