Chapters
20 Chapters
|
1:32:53
|
Login to bookmark this video
-
Course Code
Subscribe to download the code!Compatible PHP versions: >=5.3.3
Subscribe to download the code!Compatible PHP versions: >=5.3.3
-
This Video
Subscribe to download the video!
Subscribe to download the video!
-
Subtitles
Subscribe to download the subtitles!
Subscribe to download the subtitles!
-
Course Script
Subscribe to download the script!
Subscribe to download the script!
03.
Handling data with a Form
Scroll down to the script below, click on any sentence (including terminal blocks) to jump to that spot in the video!
Subscribe to jump to this part in the video!
This tutorial uses an older version of Symfony. The concepts of REST are still valid, but I recommend using API Platform in new Symfony apps.
What PHP libraries does this tutorial use?
// composer.json
{
"require": {
"php": ">=5.3.3",
"symfony/symfony": "2.6.*", // v2.6.11
"doctrine/orm": "~2.2,>=2.2.3,<2.5", // v2.4.7
"doctrine/dbal": "<2.5", // v2.4.4
"doctrine/doctrine-bundle": "~1.2", // v1.4.0
"twig/extensions": "~1.0", // v1.2.0
"symfony/assetic-bundle": "~2.3", // v2.6.1
"symfony/swiftmailer-bundle": "~2.3", // v2.3.8
"symfony/monolog-bundle": "~2.4", // v2.7.1
"sensio/distribution-bundle": "~3.0,>=3.0.12", // v3.0.21
"sensio/framework-extra-bundle": "~3.0,>=3.0.2", // v3.0.7
"incenteev/composer-parameter-handler": "~2.0", // v2.1.0
"hautelook/alice-bundle": "0.2.*", // 0.2
"jms/serializer-bundle": "0.13.*" // 0.13.0
},
"require-dev": {
"sensio/generator-bundle": "~2.3", // v2.5.3
"behat/behat": "~3.0", // v3.0.15
"behat/mink-extension": "~2.0.1", // v2.0.1
"behat/mink-goutte-driver": "~1.1.0", // v1.1.0
"behat/mink-selenium2-driver": "~1.2.0", // v1.2.0
"phpunit/phpunit": "~4.6.0" // 4.6.4
}
}
18 Comments
Something that's clear as mud is WHY I would want to include all this form business in the API controller. I have two guesses:
1) You get built-in validation of submitted data, since Symfony conflates an entity with a form
2) You can use this to update an existing programmer as well as create a new one by creating the form with an entity pulled from the database, rather than a blank one.
What's lacking is information on what calling $form->submit($data) does that's useful. I'm hoping this becomes clear in the next section or two.
Hey Michael!
Actually, good question - I may have over-assumed some points. Some thoughts:
A) you can get validation without using forms. If you have an object (entity or otherwise), you can pass it directly to the validator service and get back a list of validation errors (which you could then display just in an API just as easily as with a form).
B) The form is really good at basically calling your set* functions. So the very first thing you get is the ability to avoid manually parsing through the request body and calling setName(), setDescription(), setPrice(), etc etc. But if you didn't use forms - as long as you centralized that "setting" logic somewhere, you could use it to create a new entity or update an entity.
C) The form has built-in data transformers. So, if the client sends a Y-m-d date, then your "date" field will convert this to a DateTime object before setting it on your object. Or, if the client sends some foreign key id value (e.g. imagine Product has a category_id in the database, and 5 is sent as the categoryId value in an API), the "entity" form type would convert that to the entity object (e.g. Category).
D) One of the most important things - that I didn't mention - is that eventually we'll use NelmioApiDocBundle to get some really slick API documentation. It's able to automatically read forms - meaning that it'll know exactly what input your endpoint accepts just by looking at the form that the endpoint uses. That's a big reason - but it won't show up until we talk about documentation.
P.S. I *am* a proponent, however, that if using a form gets too tough or confusing for some reason, feel more than free to back up and just manually parse through the data yourself. That's no big deal.
Cheers!
So, then, is calling $form->submit($data) sufficient to have done all this work for us automatically? I.e., has it set all the $programmer properties for us behind the scenes, along with any data transformations? And am I correct in assuming that a call to $form->isValid() could be used here?
You got it :). submit() calls the setters (after the normal data transformations of the form). And yes, you'd absolutely be able to do a $form->isValid() - it's something we'll do in the next episode (recording now) to return a nice response with validation errors.
Hi Ryan
I'm just curious what is your opinion here? Do you think it would be better if that data binding logic was separated from the forms?
Regards,
Rob
Yo Robert!
Hmm, yea! Really, the *only* reason I'm using the form system here is for this "data binding logic": the fact that it will take the data from the request (pretty minor), run the data transformers over each piece of data to convert it to something else when necessary (major) and then set this data on the objects (minor). In a perfect world, there would be a smaller system to help us with this. At some point, I'm going to look again at using the deserializer for this... which historically I found too inflexible (but it's being used successfully in ApiPlatform, I'm told).
Let me know if that answers your question :).
Cheers!
Hi Ryan,
Sorry for the delay. Yes this does answer my question. Thank you very much. Now I know what should I do :)
Regards,
Rob
Hi Ryan.
Suppose I have a Profile entity which has links field with json type. I want to create and Rest Api which will create that entity. But I found these lines of code which throw an exception in this case.
Form.php:538
.....
elseif (\is_array($submittedData) && !$this->config->getCompound() && !$this->config->hasOption('multiple')) {
$submittedData = null;
$this->transformationFailure = new TransformationFailedException('Submitted data was expected to be text or number, array given.');
}
Hey Andranik H.
I think what you need is a DataTransformer, so you can transform the submitted data before validating it.
You can learn more about DataTransformers here: https://symfonycasts.com/sc...
Or at the docs: https://symfony.com/doc/cur...
Cheers!
Hello, I have a problem with the api I'm implementing. There is an entity called Report that has foreign key of the entity City (Many-To-One). I can not save the Report object. Help me please
Hey Danilo,
So your Report entity relates to the City one as ManyToOne, right? It sounds like you need to set a City on your Report entity before saving it. Try to set a City first and only then call flush().
Cheers!
in Symfony 3.0.6, $form->submit doesn't seem to validate a collection of forms.
Let's say you have an order which has some information and also an array of lines (BlanketOrderLine object).
BlanketOrderLineType is the form type for BlanketOrderLine .
Parent form is validated but not the BlanketOrderLineType ....
$builder
->add('lines', CollectionType::class,
array('entry_type' => BlanketOrderLineType::class,
'label' => false,
'allow_add' => true,
'allow_delete' => true,
'prototype' => false,
'required' => true,
'by_reference' => false,
'entry_options' => array('constraints' => [new Assert\Valid()])
));
Any idea why?
Forget about that. I upgraded from symfony 2.7 to 3. setDefaultOptions is gone and need to use the configureOptions.
Hey, Sylvain Cyr !
You are totally right! The setDefaultOptions() method was removed in favor of configureOptions() in Symfony 3. The best way is to upgrade to the Symfony 2.8 first, fix all deprecations and then move up to the 3.x.
Cheers!
Hi, im using Symfony 3.2, and have a little bit of a problem on inserting the json data into forms. I have my Note entity, that i need to validate using forms, but i keep getting the error "Cannot use object of type AppBundle\Entity\Note as array". All im doing is creating a named builder form, and submiting with json object that i previously decoded, so it's array now. This is the code:
$note = new Note();
$form = $this->get('form.factory')->createNamedBuilder('noteForm', FormType::class, $note)
->add('type', TextType::class, [
'required' => true
])
->add('title', TextType::class, [
'required' => true
])
->add('content', TextType::class, [
'required' => true
])
->getForm();
$form->submit($data);
if($form->isValid()){
...
}
I also tried with the regular formBuilder, but i keep getting the same error. And yes, im sending data as a json object: {noteForm: {type: "note", title: "something", content: "something"}}
Can you please help me?
Thanks in advace!
Hey Nikola Dimitrijevic
Have you tried creating your own FormType for your Note class ? Just as we do in ProgrammerType
Cheers!
Yes, i did. But i worked it out in the end. So, there was a piece of code inside of $form->isValid(), and that piece of code was the following: $formData = $form->getData();
$note->setType($formData['type']);
... And the error was "Cannot use object of type AppBundle\Entity\Note as array". The thing i was doing was exactly that i was treating $formData as an array, when in reality, $formData was Note object. Rookie mistake, but at least, now i know for sure how does forms work! :)
Cheers and thanks for the answer!
I'm glad to hear you could fix the problem by yourself, keep going!
Have a nice day :)
"Houston: no signs of life"
Start the conversation!