Display a field depending on a checkbox - php

I have a form with a checkbox field and I want basically when this checkbox is checked, display a field below.
I do not know what is the best practice in symfony to do that...
Form builder :
public function buildForm(FormBuilderInterface $builder, array $options)
{
->add('protected', 'checkbox', array(
'label' => 'Protected by a password ?',
'required' => false,
'mapped' => false
))
->add('password', 'password', array(
'label' => 'Mot de passe',
'required' => false
))
}
So if the field 'protected' is checked, I want to display 'password' field.

I would do this with jquery.
Hide the field with css ( i would suggest to do this with a class instead)
->add('password', 'password', array(
'label' => 'Mot de passe',
'required' => false,
'attr' => array('style' => 'display:none;')
))
and then in jquery:
$('#checkbox_id').click(function() {
$('.password_id')[this.checked ? "show" : "hide"]();
});
I hope this helped!

Related

Validation of AJAX submitted forms in Symfony 5

I'm building an Address form in Symfony 5.1.
It is created in an AddressType Class that has some required fields.
$builder
->add('name', TextType::class, [
'required' => false,
'label' => 'address.name',
'help' => 'address.name_help',
'attr' => [
'placeholder' => 'address.name_ph',
]
])
->add('company', TextType::class, [
'required' => false,
'label' => 'address.company',
'attr' => [
'placeholder' => 'address.company_ph',
]
])
->add('first_line', TextType::class, [
'label' => 'address.first_line',
'attr' => [
'placeholder' => 'address.first_line_ph',
]
])
->add('second_line', TextType::class, [
'required' => false,
'label' => 'address.second_line',
'attr' => [
'placeholder' => 'address.second_line_ph',
]
])
->add('add_info', TextType::class, [
'required' => false,
'label' => 'address.add_info',
'help' => 'address.add_info_help',
'attr' => [
'placeholder' => 'address.add_info_ph',
]
])
->add('postcode', TextType::class, [
'label' => 'address.postcode',
'attr' => [
'placeholder' => 'address.postcode_ph',
]
])
->add('city', TextType::class, [
'label' => 'address.city',
'attr' => [
'placeholder' => 'address.city_ph',
]
])
->add('state', TextType::class, [
'required' => false,
'label' => 'address.state',
'attr' => [
'placeholder' => 'address.state_ph',
]
])
->add('country', CountryType::class, [
'label' => 'address.country',
'preferred_choices' => ['FR'],
'attr' => [
'data-toggle' => 'select',
'placeholder' => 'address.country_ph',
]
])
->add('save',
SubmitType::class,
[
'label' => $options['submit_btn_label'],
]
);
If I submit this form with the submit button, everything works as expected, my form is being processed for validation and if It detects some errors, they are shown on each field.
Here is the function that handle the form :
public function new(Request $request)
{
$user = $this->getUser();
$address = new Address();
$address->setCreatedBy($user);
$form = $this->createForm(AddressType::class, $address);
//handle form
$form->handleRequest($request);
if ($form->isSubmitted()){
//if submit, add hidden fields
$address = $form->getData();
//if valid, process
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($address);
$em->flush();
$this->addFlash(
'success',
'Your address was created.'
);
return $this->redirectToRoute('address_index');
}
}
return $this->render('address/new.html.twig', [
'form' => $form->createView(),
'mode' => 'new',
]);
}
Now, If I submit this form through an AJAX request :
$(document).on('click', '.create-address', function() {
console.log('submitting new address form...');
var $form = $(this).closest('form')
var data = $form.serializeArray();
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data
});
});
In this case, my form is processed for validation and It passes ($form->isValid() returns true) even if I don't provide some of the required fields.
This causes the process of persisting the object to occur and so I get a PDOException.
My question is:
Why is my form not handled the same way (especially at the validation step) according how I post the data ?
And how different are those two methods from the point of view of the function that handle the request ?
The required option only adds the required attribute to the markup. This forces the browser to provide a value, but doesn't add any validation server side. You can trigger validation before your ajax call and submit only if the form status is valid.
But it is recommended to add server side validation explicitly by using the constraints option in the form or annotating the target entity. Refer to the documentation for more details.

Symfony "This value should not be blank." while submitting form

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.

Sonata/AdminBundle: Selected Option

I'm new in Symfony and Sonata/AdminBundle. I would like to know how to mark selected an option when the entity has a field from other entity. For example: I have two entities: Shop and City. The Shop entity has a field called id_city.
My problem is when I'm rendering the edit form Shop because always the first id_city in the option is selected.
This is the piece of code where I'm rendering the configuration form in AdminStores class:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->tab('Tiendas')
->with('Content', array('class' => 'col-md-9'))
->add('nombreTienda', 'text')
->add('cifTienda', 'text')
->add('direccionTienda', 'text')
->add('personaContacto', 'text', array('required' => false,'empty_data' => ''))
->add('cp', 'text', array('label' => 'Código Postal', 'required' => false, 'empty_data' => '00000'))
->add('urlTienda', 'text', array('required' => false, 'empty_data' => ''))
->add('emailTienda', 'text')
->add('telefonoTienda', 'text')
->add('login', 'text')
->add('pass', 'password', array('required' => false))
->add('idMunicipio', 'entity', array(
'class' => 'AppBundle:Municipios',
'choice_label' => 'municipio',
'query_builder' => function (EntityRepository $er) {
$lista = $er->createQueryBuilder('ss')
->orderBy('ss.municipio', 'ASC');
},
'data' => $this->subject->getIdMunicipio()
)) // end array idMunicipio y add()
->add('idProvincia', EntityType::class, array(
'class' => 'AppBundle:Provincias',
'label' => 'Provincia',
'choice_label' => 'provincia',
'choice_value' => 'getId',
'by_reference' => true,
))
->add('descripcionTienda', 'textarea')
->end()
->end()
->tab('Multimedia')
->with('Content', array('class' => 'col-md-3'))
->add('fotoTienda', 'file', array(
'label' => 'Imagenes (puedes subir hasta 6 imágenes)',
'attr' =>array('class' => 'form-control', 'multiple' => 'multiple', 'accept' => 'image/*'),
'data_class' => null,
'required' => false,
'empty_data' => 'noDisponible',
));
}
In this piece of code, I'm recovering all cities in AdminStores class:
->add('idMunicipio', 'entity', array(
'class' => 'AppBundle:Municipios',
'choice_label' => 'municipio',
'query_builder' => function (EntityRepository $er) {
$lista = $er->createQueryBuilder('ss')
->orderBy('ss.municipio', 'ASC');
},
'data' => $this->subject->getIdMunicipio()
)) // end array idMunicipio y add()
I would like to know, please, the logic for " if this->id_city == entity->id_city then, option is selected".
Thanks in advance
I edit this comment because I think that I solved it.
In my AdminController called ShopsAdmin I have created a method called getAllMunicipios which return an array with their name and id:
$allCities = array(
'Tokyo' => 1
'Madrid => 2
);
This is the method:
protected function getAllMunicipios()
{
$municipios = $this->getConfigurationPool()
->getContainer()
->get('doctrine')
->getRepository('AppBundle:Municipios')
->findBy([], ['municipio' => 'ASC']);
$todosmunicipios = array();
foreach ($municipios as $municipio) {
$todosmunicipios[(string)$municipio->getMunicipio()] = (int)$municipio->getId();
}
return $todosmunicipios;
}
Now my AdminStores::configureFormFields method like that this:
->add('idMunicipio', 'choice', array(
'choices' => $this->getAllMunicipios(),
'required' => false,
'by_reference' => false,
'data' => $this->subject->getIdMunicipio()
))
It is a good way to do it? I think that the method that return all, must be placed into the entity and not int the controller but I dont know how do it static
just call setCity(\AppBundle\Entity\City $city) in your Shop entity. and give the right city entity as the first and only parameter. Do this before you render the form

how to create dynamic form in symfony2

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.

Symfony2 select option other

I'm building a form in Symfony2, in a itemType.
Currently, users can type whatever they want in the "typePresentation" field.
I want to let them select 3-4 options (most usual options), and when they select "others", a text field appear and they can type whatever they want.
I think that I can use some jQuery to show a text field when a particular option is selected, but I want to know how to generate 2 fields with the same name, or how to save 1 of 2 fields on the same field of entity.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('numero', 'hidden')
->add('etat', 'choice', array(
'choices' => array('v' => 'Vert', 'o' => 'Orange', 'r' => 'Rouge'),
'preferred_choices' => array('v'),
'required' => true,
'expanded' => false,
'multiple' => false))
->add('typePresentation', 'text', array('attr' => array('placeholder' => 'Type de la présentation')))
->add('datePresentation', 'date', array('empty_data' => new \DateTime(),'label' => 'Date de présentation', 'years'=>range(date('Y')-2, date('Y')+5)))
->add('iteration', 'textarea', array('attr' => array('placeholder' => "Nom de l'itération")))
->add('contenu', 'textarea', array('attr' => array('placeholder' => "Contenu de l'Item")))
->add('enregistrer', 'submit');
;
}

Categories