Symfony 2拥有字段类型 - 始终“此值无效”错误

时间:2013-11-23 13:58:21

标签: php forms symfony formbuilder

我创建了一个名为“gamesetting”的新表单字段类型。此类型应根据数据数组的值处理文本输入和复选框。表单是正确构建的,但是当我提交表单时,如果输入的值不为空,我总是会收到错误“此值无效”。如果未选中该复选框或文本字段为空,则表单有效。

表单仅使用键值数组作为数据输入,而不是模型/实体对象。

<?php

namespace asdf\WebinterfaceBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;


class GamesettingType extends AbstractType {
    function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setRequired([ 'field_type' ]);
        $resolver->setDefaults([
            'label' => false,
            'field_type' => 'text',
            'required' => false
        ]);
    }

    function getName() {
        return 'gamesetting';
    }

    function getParent() {
        return 'form';
    }

    function buildView(FormView $view, FormInterface $form, array $options) {
        $view->vars['field_type'] = $options['field_type'];
    }
}

动作方法如下:

public function settingsAction(Request $request) {
    $user = $this->get('security.context')->getToken()->getUser();
    $game = GameFactory::factory(PortlistFactory::byUserAndActive($user->getUsername()));

    // Generate the settings form. Each setting has a internal identifier,
    // a type (which form element) and a label. The label is equal to the
    // identifier and will be translated with the corresponding i18n key.
    $form = $this->createFormBuilder();
    foreach ($game->getSettings()->read('config') as $key => $value) {
        $sanitized_key = str_replace('.', '_', $key);
        $sanitized_value = in_array($value, ['true', 'false']) ? !!($value == 'true') : $value;
        $type = (in_array($value, ['true', 'false'])) ? 'checkbox' : 'text';

        if ($type == "text") {
            $form->add($sanitized_key, 'gamesetting', [
                'field_type' => 'text',
                'data' => $sanitized_value,
            ]);
        } elseif ($type == "checkbox") {
            $form->add($sanitized_key, 'gamesetting', [
                'field_type' => 'checkbox',
                'data' => $sanitized_value,
            ]);
        }

    }
    $form = $form->getForm();

    $form->handleRequest($request);

    if ($form->isValid()) {
        var_dump($form->getData());

        exit;
    }

    return [
        'game' => $game,
        'form' => $form->createView()
    ];
}

1 个答案:

答案 0 :(得分:0)

创建Symfony表单元素时,它们具有各种具有默认值的属性。其中一个是'required',默认为true。

http://symfony.com/doc/2.7/reference/forms/types/text.html#required

如果您使用的浏览器支持HTML5表单验证,如果您尝试使用required = true为任何Symfony表单元素提交空值,则会显示错误。出于这个原因,我总是在构造表单字段时设置required = false。这使您可以控制表单验证。