Symfony在控制器方法中获取单个表单字段值

时间:2017-09-22 07:37:55

标签: php forms symfony symfony-2.8

我使用symfony 2.8,我正在向registerAction方法提交注册。当我在registerAction方法中使用$form-getdata()时,我收到了所有提交的数据。

AppBundle\Entity\User Object
(
    [id:AppBundle\Entity\User:private] => 
    [name:AppBundle\Entity\User:private] => testname
    [email:AppBundle\Entity\User:private] => test@test.com
    [roles:AppBundle\Entity\User:private] => Admin User
    [plainPassword:AppBundle\Entity\User:private] => 123456
    [password:AppBundle\Entity\User:private] => 
)

我使用$request->request->get('name')来获取单个名称值,但它显示的是空白屏幕并且没有打印任何内容。

我的html表单在浏览器中查看源代码时看起来像这样。

<form name="user" method="post" novalidate="novalidate">
            <div class="form-group">
                <div><label for="user_name" class="required">Name</label><input type="text" id="user_name" name="user[name]" required="required" class="form-control" /></div>
            </div>
            <div class="form-group">
                <div><label for="user_email" class="required">Email</label><input type="email" id="user_email" name="user[email]" required="required" class="form-control" /></div>
            </div>
            <div class="form-group">
                <div><label for="user_roles" class="required">Roles</label><select id="user_roles" name="user[roles]" class="form-control" style="margin:5px 0;"><option value="Normal User">Normal User</option><option value="Admin User">Admin User</option></select></div>
            </div>
            <div class="form-group">
                <div><label for="user_plainPassword_first" class="required">Password</label><input type="password" id="user_plainPassword_first" name="user[plainPassword][first]" required="required" class="form-control" /></div>
            </div>
            <div class="form-group">
                <div><label for="user_plainPassword_second" class="required">Repeat Password</label><input type="password" id="user_plainPassword_second" name="user[plainPassword][second]" required="required" class="form-control" /></div>
            </div>
            <div><button type="submit" id="user_Register" name="user[Register]" class="btn btn-success form-control">Register</button></div><input type="hidden" id="user__token" name="user[_token]" value="epZFHVctxHFlsnxG-H4OdS92DmGVjP1DDF-bKJrV2Ss" />
    </form>

如何获得单张发布的表单值。?

1 个答案:

答案 0 :(得分:1)

如果$request->request->get('{form_name}')返回包含表单数据的数组,则可以使用$request->request->get('user')['name']访问特定输入字段。但是你应该使用表单类,在那里你可以用验证约束定义所有必要的字段,等等。希望这会有所帮助!