Symfony 3 - Best practice for concating form-blocks - php

I'm trying to learn how to build forms in symfony 3.
Following some tutorials I have built a PersonType
class PersonType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('gender', ChoiceType::class, array('label' => 'Anrede', 'choices' => array('Herr' => 'Herr', 'Frau' => 'Frau'), 'attr' => array('class' => 'form-control')))
->add('title', TextType::class, array('label' => 'Titel', 'attr' => array('class' => 'form-control')))
->add('firstname', TextType::class, array('label' => 'Vorname', 'attr' => array('class' => 'form-control')))
->add('lastname', TextType::class, array('label' => 'Nachname', 'attr' => array('class' => 'form-control')))
->add('birthdate', DateType::class, array('label' => 'Geburtsdatum', 'attr' => array('class' => 'form-control')))
->add('street', TextType::class, array('label' => 'Straße', 'attr' => array('class' => 'form-control')))
->add('streetnumber', TextType::class, array('label' => 'Hausnummer', 'attr' => array('class' => 'form-control')))
->add('zip', TextType::class, array('label' => 'PLZ', 'attr' => array('class' => 'form-control')))
->add('city', TextType::class, array('label' => 'Stadt', 'attr' => array('class' => 'form-control')))
->add('email', TextType::class, array('label' => 'E-Mail', 'attr' => array('class' => 'form-control')));
}
public function getName() {
return 'person';
}
}
And some other types.
In the controller I have
$person = new Person();
$form = $this->createForm(PersonType::class, $person);
My question now is, how do I now concat the PersonType to some other Types to get one Form out of it? And how do I then set the submit-button?

You cannot concatenate but you can include a subset of fields in several forms.
Here you have a nice example in the Symfony documentation :
http://symfony.com/doc/current/cookbook/form/inherit_data_option.html
Recap :
Create a form with your subfields, with the option 'inherit_data' => true.
Use it in another form as field.

First of all, please note how you add fields to PersonType form, because it will be exactly the same.
->add('email', TextType::class, array('label' => 'E-Mail', 'attr' => array('class' => 'form-control')));
What you do here is adding a subform TextType. It actually contains single field, but it's still a form.
The same way you can add PersonType to any other form. That would be something like:
->add('person', PersonType::class, array(/* some options if needed*/);
And how do I then set the submit-button?
As mentioned in Best Practices for Symfony Forms, I would suggest to add them in template, not to the form object.

Related

How to show field value in sonata edit form?

There is edit form. One field should not be editable. I have tried to set options disabled=true, attr => ['readonly' => true], they make it uneditable, but when submitting form, it gets submitted, sets null to that field and then I get error when getting that field value because it cannot be null.
So I want to make that field not even exist as field but show its value in edit form. Is there a way to do it? Or also if you know how to get rid of error when submitting form with disabled field, that would work too.
public function configureFormFields(FormMapper $form)
{
if ($this->subject->getId() === null) {
$form
->add('name', 'text', ['required' => true])
->add('codeMod', 'text', ['required' => true])
->add('position', 'text', ['required' => false])
->add('projectMod', EntityType::class, ['class' => ProjectEntity::class])
->add('active', 'checkbox', ['required' => false])
->add('first', 'checkbox', ['required' => false])
->add('last', 'checkbox', ['required' => false])
->add('denialReasons', 'text', ['required' => false])
;
} else {
$form
->add('name', 'text', ['required' => true])
->add('position', 'text', ['required' => false])
// ->add('project', TextType::class, ['label' => 'form.label_project_mod', 'attr' => [/*'readonly' => true,*/ 'disabled' => true]])
->add('project', EntityType::class,
['label' => 'form.label_project_mod', 'class' => ProjectEntity::class, 'attr' => ['readonly' => true, 'disabled' => true],
// 'template' => 'ClaimClaimBundle:ClaimStatusAdmin:show_project.html.twig'
]
)
// ->add('projectMod', TextType::class, ['label' => 'form.label_project_mod', 'attr' => [/*'readonly' => true,*/ 'disabled' => true]])
->add('active', 'checkbox', ['required' => false])
->add('first', 'checkbox', ['required' => false])
->add('last', 'checkbox', ['required' => false])
->add('denialReasons', 'text', ['required' => false])
;
}
}
Currently I get error:
Type error: Return value of Qms\ClaimComponent\Status\ManagedModel\StatusManaged::getProject() must implement interface Qms\CoreComponent\Domain\Project\ManagedModel\ProjectManagedInterface, null returned
That is because field value is set to null if I have disabled field.
One way could be rewrite edit.html.twig, now sonatas default template is used. But I did not find quick way, if I override, the styling is off. For one field looks bit too much.
If you don't mind that field's value when submitting you can unmap it by setting
'mapped' => false
in its attributes.
Example:
->add('name', 'text', ['required' => true, 'mapped' => false])

Symfony - checkbox form

I have trouble with syntax, my form does not show a checkbox in a right way. Any ideas?
$form = $this->createFormBuilder()
->add('generate', CheckboxType::class, array('label' => 'Generate', 'attr' => ['class'=>'form-control']))
->add('save', SubmitType::class, array('label' => 'Send', 'attr' => [
'class' => 'btn btn-primary action-save'
]))
->getForm();

Symfony Add bootstrap form-control class

I'm using symfony 2.8, I have created one registration form, I want to add bootstrap form-control class to both password and repeat password form fields.
$builder
->add('name', TextType::class,array(
'attr' => array(
'class' => 'form-control'
)
))
-> add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
'attr' => array('class' => 'form-control')
));
Incase of 'name' field its working BUT for password fields the class is not adding.
How can I add 'form-control' class for password fields.
Any help is much appreciated.
Thanks.
There are two ways of doing this. The first is to use options, which will pass the options down to each of the underlying fields:
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
'options' => array('attr' => array('class' => 'form-control'))
));
You can also add the class in the first_options and second_options field, like so. This would be useful if you had options that were specific to each field or you wanted to override something from the main options.
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array(
'label' => 'Password',
'attr' => array('class' => 'form-control')
),
'second_options' => array(
'label' => 'Password',
'attr' => array('class' => 'form-control-override')
),
'attr' => array('class' => 'form-control')
));
Also, as of Symfony 2.6 it has has built-in Bootstrap form theme support to where you shouldn't have to be adding these classes to all of your fields manually.
Some guys from the Symfony development team, suggest that you should use the boostrap's classes directly in html (here, if you want to see the suggestion). And the suggestion makes perfect sens to me, as Symfony is for backend development, and not frontend. So the ideal way of solving this is to create your two fields in the Type class, and when rendering the form, add something like:
{{ form_row(name, { attr: { 'class': 'form-control' } ) }}
{{ form_row(password, { attr: { 'class': 'form-control' } ) }}
{{ form_row(plainPassword, { attr: { 'class': 'form-control' } ) }}

Symfony2 404 error: Object Not Found (ParamConverter error)

I created a new boundary class called search.html.twig, but when I go to the URL (http://localhost:8000/shrubs/search) I get the following error:
ERROR - Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "AppBundle\Entity\Shrubs object not found." at C:\Users\rosmith\shrub_search\vendor\sensio\framework-extra-bundle\Request\ParamConverter\DoctrineParamConverter.php line 66
There must be something wrong with my ParamConverter? Are my annotations correct? I read the symfony documentation but it just doesn't make sense to me. Here's my controller:
/**
* Finds and displays a shrub entity.
*
* #Route("/search", name="shrubs_search")
* #ParamConverter("post", class="AppBundle:Shrubs")
*/
private function searchAction(Request $request)
{
$shrub = new Shrubs();
$form = $this->createForm('AppBundle\Form\ShrubsType', $shrub)
->add('botanicalname', TextType::class, array('label' => 'Botanical Name:'))
->add('commonname', TextType::class, array('label' => 'Common Name:'))
->add('wetsoil', CheckboxType::class, array('label' => 'Tolerates Wet Soil:'))
->add('moistsoil', CheckboxType::class, array('label' => 'Prefers Moist Soil:'))
->add('peatysoil', CheckboxType::class, array('label' => 'Prefers Peaty Soil:'))
->add('welldrainedsoil', CheckboxType::class, array('label' => 'Prefers Well-drained Soil:'))
->add('drought', CheckboxType::class, array('label' => 'Tolerates Drought:'))
->add('claysoil', CheckboxType::class, array('label' => 'Tolerates Clay Soil:'))
->add('sandysoil', CheckboxType::class, array('label' => 'Prefers Sandy Soil:'))
->add('loamsoil', CheckboxType::class, array('label' => 'Prefers Loam Soil:'))
->add('infertilesoil', CheckboxType::class, array('label' => 'Tolerates Infertile Soil:'))
->add('richsoil', CheckboxType::class, array('label' => 'Prefers Rich Soil:'))
->add('compactedsoil', CheckboxType::class, array('label' => 'Tolerates Compacted Soil:'))
->add('cityconditions', CheckboxType::class, array('label' => 'Tolerates City Conditions:'))
->add('pollution', CheckboxType::class, array('label' => 'Tollerates Pollution:'))
->add('salt', CheckboxType::class, array('label' => 'Tolerates Salt Conditions:'))
->add('windy', CheckboxType::class, array('label' => 'Tolerates Windy Conditions:'))
->add('shade', CheckboxType::class, array('label' => 'Prefers Shade:'))
->add('partshade', CheckboxType::class, array('label' => 'Prefers Part Shade:'))
->add('fullsun', CheckboxType::class, array('label' => 'Prefers Full Sun:'))
->add('pestproblem', CheckboxType::class, array('label' => 'Pest Problem:'))
->add('borderlinehardy', CheckboxType::class, array('label' => 'BorderLine Hardy'));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($shrub);
$em->flush($shrub);
return $this->redirectToRoute('shrubs_show', array('id' => $shrub->getNumber()));
}
return $this->render('shrubs/new.html.twig', array(
'shrub' => $shrub,
'form' => $form->createView(),
));
}
Your route should contain post param.
#Route("/search/{post}", name="shrubs_search")
Also your method should take this param as method argument.

Symfony2 form type entity add extra option

I have the following Symfony form field, it's a drop down that loads from an entity:
->add('measureunit', 'entity', array('label' => 'Measure Unit',
'class' => 'TeamERPBaseBundle:MeasureUnit',
'expanded' => false, 'empty_value' => '',
'multiple' => false, 'property' => 'abreviation'
))
As you can see I have added 'empty_value' => '' and everything works fine. Now, what I want is to have an extra option at the end to add a let say new measure unit. In other words the dropdown should display all the content of my entity, the empty value and other extra option called new measure unit or what ever I want to call it. Is it possible?
Edit: The whole form type file has this:
<?php
namespace TeamERP\StoresBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array('label'=>'Product name', 'required' => true,
'attr' => array('class' => 'form-control')))
->add('code', 'text', array('label'=>'Code', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('description', 'text', array('label'=>'Description', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('cost', 'money', array('label'=>'Cost', 'divisor' => 100, 'currency' => 'BWP'))
->add('category', new CategoryType(), array('required' => false))
->add('measureunit', 'entity', array('label' => 'Measure Unit',
'class' => 'TeamERPBaseBundle:MeasureUnit',
'expanded' => false, 'placeholder' => '',
'multiple' => false, 'property' => 'abreviation'
))
->add('qtyToPurchase', 'number', array('label'=>'Quantity to purchase', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('reorderPoint', 'number', array('label'=>'Reorder point', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('qtyOnSalesOrder', 'number', array('label'=>'Quantity on sales order', 'required' => false,
'attr' => array('class' => 'form-control')));
}
public function getName()
{
return 'product';
}
public function finishView(FormView $view, FormInterface $form, array $options)
{
$new_choice = new ChoiceView(array(), 'add', 'add new'); // <- new option
$view->children['measureunit']->vars['choices'][] = $new_choice;//<- adding the new option
}
}
Error:
Compile Error: Declaration of TeamERP\StoresBundle\Form\Type\ProductType::finishView() must be compatible with Symfony\Component\Form\FormTypeInterface::finishView(Symfony\Component\Form\FormView $view, Symfony\Component\Form\FormInterface $form, array $options)
Edit2 Working form file:
<?php
namespace TeamERP\StoresBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array('label'=>'Product name', 'required' => true,
'attr' => array('class' => 'form-control')))
->add('code', 'text', array('label'=>'Code', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('description', 'text', array('label'=>'Description', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('cost', 'money', array('label'=>'Cost', 'divisor' => 100, 'currency' => 'BWP'))
->add('category', new CategoryType(), array('required' => false))
->add('measureunit', 'entity', array('label' => 'Measure Unit',
'class' => 'TeamERPBaseBundle:MeasureUnit',
'expanded' => false, 'placeholder' => '',
'multiple' => false, 'property' => 'abreviation'
))
->add('qtyToPurchase', 'number', array('label'=>'Quantity to purchase', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('reorderPoint', 'number', array('label'=>'Reorder point', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('qtyOnSalesOrder', 'number', array('label'=>'Quantity on sales order', 'required' => false,
'attr' => array('class' => 'form-control')));
}
public function getName()
{
return 'product';
}
public function finishView(FormView $view, FormInterface $form, array $options)
{
$new_choice = new ChoiceView(array(), 'add', 'add new'); // <- new option
$view->children['measureunit']->vars['choices'][] = $new_choice;//<- adding the new option
}
}
In your form type override the function finishView:
public function buildForm(FormbuilderInterface $builder, array $options){
$builder->add('measureunit', EntityType::class, array(
'label' => 'Measure Unit',
'class' => 'TeamERPBaseBundle:MeasureUnit',
'expanded' => false,
'empty_value' => '',
'multiple' => false,
'property' => 'abbreviation'
));
}
public function finishView(FormView $view, FormInterface $form, array $options)
{
$newChoice = new ChoiceView(array(), 'add', 'Add New'); // <- new option
$view->children['measureunit']->vars['choices'][] = $newChoice;//<- adding the new option
}
You will get a new option 'add new' with value 'add' to the bottom of the field.
In addition to accepted answer:
If you choose the added option you will get validation error (because it's not valid entity), the following snippet can be used to overcome this error:
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) {
if ($event->getData() === 'add') {
$event->setData(null);
}
}
);
Then you can check if selected option is NULL, if it's => take value from additional input field.

Categories