简体   繁体   中英

Symfony 2/3 REST API Validation without form

For example I have entity Cat with property $name(string).

I send to url POST /cats with parameter [name = 123]

How I can validate data from request without form? Or REST API with form validation it's normal? I can't find information about validation without form. I can use Validation component without form, but maybe exists some bundle who can give me better approaches than $this->get('validator')->validate('data from request').

Thanks.

I'd recommend still using a Form to handle validation, and you can simulate the submit manually: http://symfony.com/doc/current/form/direct_submit.html#calling-form-submit-manually

A very simplified example could then be something like below.

$formFactory = new Symfony\Component\Form\FormFactory();

//build your "post" data from your submitted content via api
$data = json_decode($request->getContent(), TRUE);

//build your Form and Entity objects.
$formType = new Path\To\CatForm(); //for example
$entity = new Path\To\CatEntity();

$parameters = array();
$method = 'POST';

$form = $formFactory->create($formType, $entity, ['method' => $method]);
$form->submit($parameters, ($method == 'PATCH' ? false : true));

if ($form->isValid()) {
    //do stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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