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.
Related
I'm trying to submit a user form. But the form does not contain all database fields because I want to set the password later (when submitting form).
But now I'm getting the error that the field 'password' should not be blank. Removing the form validation is not working and adding them as HiddenType is also not working.
I'm getting this error after the $form->isValid() check
EDIT:
FormBuilder
$form = $this->createFormBuilder($user)
->add('email', TextType::class, array(
'label' => 'Email adres',
'attr' => array(
'class' => 'input-field'
)
))
->add('first_name', TextType::class, array(
'attr' => array(
'label' => 'Voornaam',
'class' => 'input-field'
)
))
->add('middle_name', TextType::class, array(
'label' => 'Tussenvoegsel (optioneel)',
'required' => false,
'attr' => array(
'class' => 'input-field'
)
))
->add('last_name', TextType::class, array(
'label' => 'Achternaam',
'attr' => array(
'class' => 'input-field'
)
))
->add('date_of_birth', DateType::class, array(
'label' => 'Geboortedatum',
'attr' => array(
'class' => 'input-field'
)
))
->add('save', SubmitType::class, array(
'label' => 'Gebruiker Opslaan',
'attr' => array(
'class' => 'form-submit-btn'
)
))
->getForm();
Submitting the form:
$form->handleRequest($request);
if($form->isSubmitted()){
if($form->isValid()){
dump($user);
exit;
}
}
EDIT:
Doing $user->setPassword('123'); before validation is not working
Can you post your User Entity?
You may get the Error because an argument is not allowed to be blank.
Take a look at any #Assert\NotBlank or nullable = false Annotations.
Can you show your User class? May be implements UserInterface? So, there is this validation.
I'm trying to generate a JSON of my form type in my controller using liform or liform-bundle but got the error :
CRITICAL - Uncaught PHP Exception Symfony\Component\Debug\Exception\UndefinedMethodException: "Attempted to call an undefined method named "getBlockPrefix" of class "Symfony\Component\Form\Extension\DataCollector\Proxy\ResolvedTypeDataCollectorProxy"." at /home/admin/Documents/displayce/code/vendor/limenius/liform/src/Limenius/Liform/FormUtil.php line 39
the code in my controller :
$form = $this->createForm(new FormType(), $entity, array(
'method' => 'PUT',
'csrf_protection' => false,
));
$schema = json_encode($this->get('liform')->transform($form));
My form type code :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('startDate', 'date', array(
'label' => 'Start Date',
'required' => false,
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
'input' => 'datetime',
))
->add('endDate', 'date', array(
'label' => 'End Date (included)',
'required' => false,
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
'input' => 'datetime',
))
->add('name', 'text', array(
'label' => 'Name',
'max_length' => 255,
))
->add('budget', 'money', array(
'label' => 'Budget (target)',
'required' => true,
'scale' => 0, // not showing decimals
))
->add('target', 'targeting', array(
'cascade_validation' => true,
));
}
and the targeting type :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('contexts', 'entity', array(
'label' => 'Context(s)',
'class' => 'AppBundle\Entity\Context',
'choice_label' => 'name',
'expanded' => false,
'multiple' => true,
'required' => false,
))
->add('contextDetails', 'entity', array(
'label' => 'Detailed Context(s)',
'class' => 'AppBundle\Entity\ContextDetail',
'choice_label' => 'name',
'group_by' => 'context.name',
'expanded' => false,
'multiple' => true,
'required' => false,
))
->add('dataVariables', 'entity', array(
'label' => 'Variable',
'class' => 'AppBundle\Entity\DataVariable',
'choice_label' => 'name',
'expanded' => false,
'multiple' => true,
'group_by' => function($dataVariable, $key, $index) {
return $dataVariable->getDataProvider()->getName();
}
))
// Include criteria
->add('region', 'choice', array(
'label' => 'Region(s)',
'choices' => RegionDepartment::$regions,
'expanded' => false,
'multiple' => true,
'required' => false,
))
->add('department', 'choice', array(
'label' => 'Department(s)',
'choices' => RegionDepartment::$departments,
'expanded' => false,
'multiple' => true,
'required' => false,
))
;
It might be because I use a nested formtype ?
My goal if to combine symfony FormType with React Component so as long as you can redirect me to a solution to do that, i will me glad.
add a getBlockPrefix to your formType and targeting type like this :
public function getBlockPrefix()
{
return 'name of your form type';
}
I forked the bundle to change ->getBlockPrefix to ->getName() since the first one is not in Form.php in Symfony 2.7
I have for with fields type entity, drop down choice and required true but when submit form have error in console
An invalid form control with name='inbound_invoice_row[costObject]' is not focusable.
new:1 An invalid form control with name='inbound_invoice_row[accountingAccount]' is not focusable.
new:1 An invalid form control with name='inbound_invoice_row[user]' is not focusable.
Another field validate fine, like vat or price but for accountingAccount user costObject have this error in console
why not understand
my form
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('location', EntityType::class, [
'class' => Location::class,
'empty_value' => 'select_default_value',
'query_builder' => self::getLocations(),
'required' => false,
'label' => 'locations',
'translation_domain' => 'invoicing'
])
->add('costObject', EntityType::class, [
'class' => CostObject::class,
'empty_value' => 'select_default_value',
'choices' => self::getCostObjectHierarchy(),
'required' => true,
'label' => 'cost_object',
'translation_domain' => 'invoicing'
])
->add('accountingAccount', EntityType::class, [
'class' => AccountingAccount::class,
'empty_value' => 'select_default_value',
'query_builder' => self::getAccountingAccount(),
'required' => true,
'label' => 'accounting_account',
'translation_domain' => 'invoicing'
])
->add('user', EntityType::class, [
'class' => User::class,
'empty_value' => 'select_default_value',
'choices' => self::getR(),
'required' => true,
'label' => 'employee',
'translation_domain' => 'invoicing'
])
->add('description', TextType::class, [
'label' => 'description',
'required' => false,
'translation_domain' => 'invoicing'
])
->add('vat', ChoiceType::class, [
'choices' => $this->vatClasses,
'required' => true,
'label' => 'vat',
'translation_domain' => 'common'
])
->add('price', TextType::class, [
'label' => 'price',
'required' => true,
'translation_domain' => 'invoicing'
]);
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'EconomyBundle\Entity\InboundInvoiceRow',
'locations' => [],
'employees' => [],
'accounts' => [],
'vat' => [],
'cost' => [],
'ajax' => true,
'csrf_protection' => true
));
}
public function getName()
{
return 'inbound_invoice_row';
}
create form in action
$form = $this->createForm(
$this->get('economy.form.type.in_bound_invoice_row'),
$inboundInvoiceRow,
[
'validation_groups' => [InboundInvoiceRow::GROUP_POST],
'cascade_validation' => true,
'action' => $this->generateUrl('inbound_invoices_row_create', ['id' => $inboundInvoice->getId()]),
'method' => 'POST',
]
);
$form->add('submit', 'submit', array('label' => 'save', 'translation_domain' => 'invoicing'));
You probably have some js library that is used when rendering those fields (e.g. Select2 or Chosen). When there's some HTML validation error (e.g. the field is required but there is no value) on a field, but it's not visible - it might have display property set to none - then the browser is unable to attach error message to that field. This is what most likely triggers your error.
Simplest solution is to set 'required' => false in form type options and rely on backend validation (e.g. using Symfony Validation component) rather than on basic HTML validation.
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!
Is it possible to generate select list where options will be retrieved from database and there will be option (with JS) to multiply field ?
I've copied my code, maybe it will help.
$builder->add('device', 'collection', array(
'type' => 'entity',
'label' => ' ',
'options' => array(
'class' => 'TrashTrashAdminBundle:DeviceType',
'property' => 'name',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('d')
->where('d.isLighting = 1');
},
),
'attr' => array('class' => 'form-control device')
))
You are trying to work with collection field type in way as you would work with entity field type. You should change collection for entity:
$builder->add('device', 'entity', array(
'options' => array(
'class' => 'TrashTrashAdminBundle:DeviceType',
'property' => 'name',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('d')
->where('d.isLighting = 1');
},
),
'attr' => array(
'class' => 'form-control device'
))
);
After the select box is generated, you can make changes, which you mentioned, at your will.