Reputation: 69
Trying to get up to speed with Symfony, going thru the tutorial, and on this page (symfony.com/doc/current/forms.html) is the following sample:
$form = $this->createFormBuilder($task)
->add('task', TextType::class)
->add('dueDate', DateType::class)
->add('save', SubmitType::class, array('label' => 'Create Post'))
->getForm();
return $this->render('default/new.html.twig', array(
'form' => $form->createView(),
));
Having never seen this syntax before, I quickly ruled out call-chaining which it superficially appears to be, then found that interpreting each of the "bare" arrows as pointing to methods of $form
was mostly correct. It ended up working correctly in this version:
$formBuilder = $this->createFormBuilder($task);
$formBuilder->add('task', TextType::class);
$formBuilder->add('dueDate', DateType::class);
$formBuilder->add('save', SubmitType::class, array('label' => 'Create Post'));
$form = $formBuilder->getForm();
return $this->render('default/new.html.twig', array(
'form' => $form->createView(),
));
So I'm trying to understand the original sample. If the correct interpretation of the seemingly disconnected arrows is "call method of the object named on the first line", this explains all except the line "->getForm();
". If the same rule is applied to that line, however, that line becomes "$formBuilder->getForm();
", which of course fails on the render() line because of the lack of assignment to $form (I mean, it still would have failed even if I'd kept the name $form for the builder).
So is there a mistake in the tutorial, or what subtleties of syntax am I missing?
I've searched extensively with combinations of ("php", "arrow", "syntax", ...) but haven't found anything about omitting the object name in a series of method calls.
Upvotes: 0
Views: 149
Reputation: 66
This is in fact method chaining. The new lines between separate method calls is only for better code readability.
This:
$formBuilder = $this->createFormBuilder($task);
$formBuilder->add('task', TextType::class);
Is equivalent to this:
$formBuilder = $this->createFormBuilder($task)
->add('task', TextType::class);
Upvotes: 0
Reputation: 230
The original sample is indeed method chaining.
If you see this example:
$form = $this->createFormBuilder($task)
->add('task', TextType::class)
->add('dueDate', DateType::class)
->add('save', SubmitType::class, array('label' => 'Create Post'))
->getForm();
It simply means that method createFormBuilder
, add
, getform
all belong to the same class $this
so they are mostly returning return $this;
from each method, for method to be chained into the next. TextType::class
and the rest are class constants.
Upvotes: 1