So I am following the documentation and I am making a form inside its own class:
<?php
namespace Mp\ShopBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
class RegisterFormType extends AbstractType
{
public function registerForm(FormBuilderInterface $builder, array $options) {
$builder
>add('title', 'choice', array(
'choices' => array('-' => '-', 'mr' => 'Mr.', 'mrs' => 'Mrs.', 'mss' => 'Miss.'),
'label' => 'Title * ',
'attr' => array('class' => 'span1')))
->add('firstName', 'text', array(
'label' => 'First Name * ',
'attr' => array('placeholder' => 'First Name')))
->add('lastName', 'text', array(
'label' => 'Last Name * ',
'attr' => array('placeholder' => 'Last Name')))
->add('Email', 'email', array(
'label' => 'Email * ',
'attr' => array('placeholder' => 'Email')))
->add('Password', 'password', array(
'label' => 'Password * ',
'attr' => array('placeholder' => 'Password')))
->add('DateOfBirth', 'date', array(
'label' => 'Date Of Birth * ',
'widget' => 'choice'))
->add('Company', 'text', array(
'label' => 'Company ',
'attr' => array('placeholder' => 'Company')))
->add('Adress', 'text', array(
'label' => 'Adress * ',
'attr' => array('placeholder' => 'Adress')))
->add('Country', 'country', array(
'label' => 'Country * ',
'attr' => array('placeholder' => 'Country')))
->add('State', 'text', array(
'label' => 'State * ',
'attr' => array('placeholder' => 'State')))
->add('City', 'text', array(
'label' => 'City * ',
'attr' => array('placeholder' => 'City')))
->add('ZipPostalCode', 'text', array(
'label' => 'Zip / Postal Code *',
'attr' => array('placeholder' => 'Zip / Postal Code')))
->add('AdditionalInformation', 'textarea', array(
'label' => 'Additional Information ',
'attr' => array('placeholder' => 'Additional Information')))
->add('HomePhone', 'number', array(
'label' => 'Home phone ',
'attr' => array('placeholder' => 'Home Phone')))
->add('MobilePhone', 'number', array(
'label' => 'Mobile phone ',
'attr' => array('placeholder' => 'Mobile Phone')))
->add('save', 'submit', array('label' => 'Register'));
}
public function getName()
{
return 'register_form_users';
}
}
It looks like a simple form. Now in my controller I want to show it:
use Mp\ShopBundle\Form\Type\RegisterFormType;
public function registerAction()
{
$em = $this->getDoctrine()->getManager();
$products = $em->getRepository('MpShopBundle:Product')->findAll();
$form = $this->createForm(new RegisterFormType());
return $this->render('MpShopBundle:Frontend:registration.html.twig', array(
'products'=>$products,
'form'=>$form->createView(),
));
}
My twig:
<h3>Your personal information</h3>
{{ dump(form) }}
{% form_theme form _self %}
{{ form(form) }}
The thing is im not getting my form. The page and the template loads fine, but not my form.
When I do {{ dump(form) }} I get something:
FormView {#2110 ▼
+vars: array:33 [▶]
+parent: null
+children: array:1 [▶]
-rendered: true
}
As you can see I am getting the form? But it is not displaying?... Why is that?
You must change your method
public function registerForm(FormBuilderInterface $builder, array $options) {
to
public function buildForm(FormBuilderInterface $builder, array $options)
Related
I have a form that has to contain a choice field which displays its content from another entity (not the entity used in the form), so this is how I tried to create it:
$user = new user();
$profils=$rep->findAll();
$form2 = $this->createFormBuilder($user,array('csrf_protection' => false))
->add('id', 'text',array('attr'=>array("autocomplete" => "off",'name'=>'login_user','required'=>'required',
'maxlength'=>'255','placeholder'=>'Matricule')))
->add('password', 'password',array('attr'=>array('autocomplete' => 'off','placeholder'=>'Mot de passe','required'=>'required')))
->add('profils', 'choice',[
'choices' => [$profils]],array('attr'=>array('mapped'=>false,'required'=>'required')))
->add('Ajouter', 'submit', array('attr' => array('class' => 'btn btn-primary btn-block rounded_btn', 'id' => 'login_btn',
'style' => "width:6vw;height:5vh;padding:0px 0px; position:relative;left:5vmin;top:1vmin;font-size:2vmin;")))
->getForm();
Pleaaaase help me, as I'm new with symfony, I may be stuck in problems you may consider stupid, I'm sorry but i couldn't find a solution myself.
I fixed it by changing the place of "'mapped'=>false" and it worked:
$form2 = $this->createFormBuilder($user,array('csrf_protection' => false))
->add('id', 'text',array('attr'=>array("autocomplete" => "off",'name'=>'login_user','required'=>'required',
'maxlength'=>'255','placeholder'=>'Matricule')))
->add('password', 'password',array('attr'=>array('autocomplete' => 'off','placeholder'=>'Mot de passe','required'=>'required')))
->add('profils', 'choice'
,array( 'choices' => array('Profils' => $profArr),'mapped'=>false),
array('attr'=>array('required'=>'required')))
->add('Ajouter', 'submit', array('attr' => array('class' => 'btn btn-primary btn-block rounded_btn', 'id' => 'login_btn',
'style' => "width:6vw;height:5vh;padding:0px 0px; position:relative;left:5vmin;top:1vmin;font-size:2vmin;")))
->getForm();
One way of doing it is this :
In the repository of profil entity create a method eg that return an array of profils e.g
class ProfilRepository extends EntityRepository
{
public function myFindAll()
{
$queryBuilder = $this->createQueryBuilder('p');
$entites = $queryBuilder->getQuery()->getArrayResult();
return $entites;
}
}
In the controller as you are doing now,
$user = new user();
// I'm asuming that Profil is an entity
$profils = $this
->getDoctrine()
->getManager()
// this should return an array
->getRepository('SdzBlogBundle:Profil')->myFindAll()
;
$form2 = $this->createFormBuilder($user, array('csrf_protection' => false))
->add('id', 'text', array(
'attr' => array(
'autocomplete' => 'off',
'name' => 'login_user',
'required' => 'required',
'maxlength' => '255',
'placeholder' => 'Matricule'
)
))
->add('password', 'password', array(
'attr' => array(
'autocomplete' => 'off',
'placeholder' => 'Mot de passe',
'required' => 'required'
)
))
->add('profils', 'choice', array(
'choices' => $profils,
array(
'attr' => array(
'mapped' => false,
'required' => 'required'
)
)
))
->add('Ajouter', 'submit', array(
'attr' => array(
'class' => 'btn btn-primary btn-block rounded_btn',
'id' => 'login_btn',
'style' => "width:6vw;height:5vh;padding:0px 0px; position:relative;left:5vmin;top:1vmin;font-size:2vmin;"
)
))
->getForm()
;
That's all for now, Good luck.
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.
I have a formtype, ContactoType, this form contain the next fields:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nombre','text', array(
'attr' => array(
'placeholder' => 'contacto.nombre'
)
))
->add('departamento', 'entity', array(
'label' => "Departamentos",
'class' => 'ProductosBundle:Departamento',
'property' => 'nombre'
))
->add('fechaEvento', 'birthday',array(
'input' => 'datetime',
'widget' => 'single_text',
'format' => 'dd-MM-yyyy',
'attr' => array(
'placeholder' => 'DD-MM-YYYY',
'class' => 'form-control')))
->add('promocion','text', array(
'attr' => array(
'placeholder' => 'contacto.promocion'
)
))
->add('apodo','text', array(
'attr' => array(
'placeholder' => 'contacto.apodo'
)
))
->add('file','file', array(
'attr' => array(
'placeholder' => 'contacto.fichero'
)
))
;
}
The Departamento entity has a field named "requiresadditional" if this is true, and promotion nickname will be displayed, if false they are hidden.
Do not know how you could get the field value "requiresadditional"...
As it should do this?Thank!
You should test your Departamento entity in a FormEvent. Read the documentation about FormEvents here.
Usually i add all the field to my symfony form and I display / hide the field by using simple javascript event.
Hi I have successfully added an extra option in my Entity Type field in Symfony.
I have the following code:
class ReportFilterType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->setMethod('GET')
->add('users', 'entity', array(
'attr' =>
array(
'class' => 'form-control',
),
'expanded' => false,
'multiple' => false,
'class' => 'AppBundle:User',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.firstName', 'ASC');
},
))
->add('dateFrom', 'date', array(
'attr' =>
array(
'id' => 'dateFrom',
'placeholder' => 'From',
'class' => 'form-control',
'data-format' => "dd/MM/yyyy",
),
'widget' => 'single_text',
'html5' => false,
))
->add('dateTo', 'date', array(
'attr' =>
array(
'id' => 'dateTo',
'placeholder' => 'To',
'class' => 'form-control',
'data-format' => "dd/MM/yyyy",
),
'widget' => 'single_text',
'html5' => false,
))
->add('filterSubmit', 'submit', array(
'attr' => array('class' => 'btn btn-default'),
'label' => 'Filter'
))
->add('pdfSubmit', 'submit', array(
'attr' => array('class' => 'btn btn-default'),
'label' => 'Export to PDF'
));
}
public function finishView(FormView $view, FormInterface $form, array $options)
{
$new_choice = new ChoiceView(new User(), 'all', 'All Employees'); // <- new option
$view->children['users']->vars['choices'][] = $new_choice;//<- adding the new option
}
public function getName()
{
return 'report_filter';
}
}
The problem here is, when I submitted my form and choose the extra option that I added it never gets valid. Why is that so? I cannot see where the problem is originating.
Thanks!
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.