简体   繁体   English

在Symfony 3上使用FosRestBundle进行表单验证的问题

[英]Form validation issue using FosRestBundle on Symfony 3

I am working on a REST webservice (FOSRestBundle 2.0.0, Symfony 3.1.3) and testing the creation of entities. 我正在研究REST Web服务(FOSRestBundle 2.0.0,Symfony 3.1.3)并测试实体的创建。 The creation itself works fine with a correct set of data but if I try to omit a required value the controller still says the form is valid. 创建本身可以正确处理一组正确的数据,但是如果我尝试省略一个必需的值,则控制器仍会说该表格有效。

The entity itself: 实体本身:

class Customer implements ExportableEntity
{
    use Traits\FilterableTrait;
    use Traits\UuidTrait;

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @Serializer\Exclude()
     * @Serializer\ReadOnly()
     */
    private $id;

    /**
     * @var int
     *
     * @ORM\Column(name="customer_index", type="integer", unique=true)
     */
     private $customerIndex;

    /**
     * @var string
     *
     * @ORM\Column(name="customerName", type="string", length=255)
     */
     private $customerName;
     // [... accessors ...]

The controller: 控制器:

/**
 * @ApiDoc(
 *      resource=false,
 *      description="Create a new customer",
 *      section="Customers",
 *      statusCode={
 *          200="Action successful",
 *          403="Authorization required but incorrect / missing information or unsufficient rights",
 *          500="Returned if action failed for unknown reasons"
 *      }
 *  )
 *
 * @param Customer $customer
 * @return RestResponse
 */
public function postCustomerAction(Request $request) {
    $manager = $this->container->get('corebundle.managers.customer');
    // Internal usage only, no link with the WS issue
    $manager->setChecksEnabled(false);

    $customer = new Customer();
    $form = $this->get('form.factory')->createNamed(null, CustomerType::class, $customer, ['csrf_protection' => false]);
    $form->handleRequest($request);

    //if ($form->isValid()) {
    if ($form->isSubmitted() && $form->isValid()) {
        print('VALID');
        exit();
        $manager->create($customer);

        // Return 201 + Location
    }

    return \FOS\RestBundle\View\View::create($form, 400);
}

And the FormType: 和FormType:

class CustomerType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('customerName', Type\TextType::class, array('label' => 'Customer name'))
            ->add('customerIndex', Type\IntegerType::class, array('label' => 'Customer Index'))
            ->add('comment', Type\TextareaType::class, array('label' => 'Comments',
                                                             'required' => false, ))
            ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array('data_class' => 'NetDev\CoreBundle\Entity\Customer'));
    }

    /**
     * @return string
     */
    public function getBlockPrefix()
    {
        return 'netdev_corebundle_customer';
    }
}

If I try to create a new Customer and omit the "customerIndex" field, I belieev that I should get an invalid form error but I ain't getting it. 如果我尝试创建一个新的Customer并忽略“ customerIndex”字段,那么我应该得到一个无效的表格错误,但我没有。

I tried to change the "handleRequest" with 我试图用更改“ handleRequest”

$form->submit([])

and

$form->submit($request->request->get($form->getName()))

to no avail. 无济于事。 If I add a "NotBlank()" constraint to the entity itself it works but I am under the impression that this would be a workaround, not a fix. 如果我向实体本身添加“ NotBlank()”约束,那么它会起作用,但我认为这将是一种解决方法,而不是解决方法。 Did I miss something ? 我错过了什么 ?

$form->isValid()

This line will verify that your submitted data respected all the constraints written in your entity files (with Assert annotation, for example @Assert\\NotBlank()). 此行将验证您提交的数据是否遵守实体文件中写入的所有约束(带有Assert批注,例如@Assert \\ NotBlank())。

So, you did not miss something. 因此,您没有错过任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM