0
我正在使用REST Web服務(FOSRestBundle 2.0.0,Symfony 3.1.3)並測試實體的創建。創建本身對一組正確的數據工作正常,但如果我嘗試省略所需的值,控制器仍然表示該表單是有效的。在Symfony 3上使用FosRestBundle進行表單驗證問題
實體本身:
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 ...]
控制器:
/**
* @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);
}
而且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';
}
}
如果我嘗試創建一個新的客戶和省略 「customerIndex」字段,我相信我應該得到一個無效的表單錯誤,但我沒有得到它。
我試着用
$form->submit([])
和
$form->submit($request->request->get($form->getName()))
改變 「的handleRequest」 無濟於事。如果我向實體本身添加「NotBlank()」約束條件,但我的印象是這是一種解決方法,而不是解決方法。我錯過了什麼 ?
的確如我所說的這種處理約束的特殊方式起作用,但是如何使用這種形式不會產生類似的結果?由於表單「知道」哪些字段是必需的/整數/其他,爲什麼「isValid()」調用不使用這個?按照設計,我身邊的錯誤? – NaeiKinDus