I'm using Symfony 4.0 framework I have a problem. I created form it works without a problem but I can't see form_errors() text, it's not working.
Where am I doing wrong in this code?
My controller:
$user = new Users();
$form = $this->createFormBuilder($user)
->add('firstName', TextType::class, array('label'=> 'Name','error_bubbling' => false))
->add('lastName',TextType::class, array('label'=> 'Lastname','error_bubbling' => false))
->add('Email', EmailType::class, array('label' => 'Email','error_bubbling' => false))
->add('Password', RepeatedType::class, array(
'type' => PasswordType::class,
'error_bubbling' => false,
'invalid_message' => 'The password fields must match.',
'options' => array('attr' => array('class' => 'password-field')),
'first_options' => array('label' => 'Password','error_bubbling' => true),
'second_options' => array('label' => 'Repeat Password'),
))
->add('Save', SubmitType::class, array('label' => 'Register'))
->getForm();
$data['form'] = $form->createView();
$form->handleRequest($request);
$errors = $validator->validate($user);
if($errors->count() > 0){
$data['errors'] = $errors;
return $this->output('user/register',$data);
}
I created form cannot get twig render. Can't see errors text
..html.twig:
{{ form_start(form) }}
{{ form_row(form) }}
{{ form_end(form) }}
Related
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();
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' } ) }}
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.
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 this issue here with Symfony3. I am pretty new at this so I have no idea where to debug.
UserController.php
public function userEdit($id, Request $request)
{
$user = $this->getDoctrine()
->getRepository('AppBundle:Users')
->find($id);
$user->setEmail($user->getEmail());
$user->setPassword($user->getPassword());
$user->setPhone($user->getPhone());
$user->setType($user->getType());
$user->setName($user->getName());
$user->setFeedback($user->getFeedback());
$user->setPicture($user->getPicture());
$user->setRating($user->getRating());
$user->setInfo($user->getInfo());
$user->setDatecreated($user->getDatecreated());
$form = $this->createFormBuilder($user)
->add('email', EmailType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('password', RepeatedType::class, array(
'type' => PasswordType::class,
'invalid_message' => 'The password fields must match.',
'options' => array('attr' => array('class' => 'password-field form-control', 'style' => 'margin-bottom:15px')),
'required' => true,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
))
->add('phone', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('type', ChoiceType::class, array('choices' => array('Client' => 'Client', 'Builder' => 'Builder'), 'attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('name', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('picture', FileType::class, array('data_class' => null,'attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('info', TextareaType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('save', SubmitType::class, array('label' => 'Register', 'attr' => array('class' => 'btn btn-primary', 'style' => 'margin-bottom:15px')))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//Get Data
$email = $form['email']->getData();
$password = $form['password']->getData();
$phone = $form['phone']->getData();
$type = $form['type']->getData();
$name = $form['name']->getData();
$picture = $form['picture']->getData();
$info = $form['info']->getData();
$now = new\DateTime('now');
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('AppBundle:Users')->find($id);
$user->setEmail($email);
$user->setPassword($password);
$user->setPhone($phone);
$user->setType($type);
$user->setName($name);
$user->setFeedback($user->getFeedback());
$user->setPicture($picture);
$user->setRating($user->getRating());
$user->setInfo($info);
$user->setDatecreated($now);
$images = base64_encode(stream_get_contents($user->getPicture()));
$em->flush();
$this->addFlash(
'notice',
'User Updated'
);
return $this->render('home/useredit.html.twig', array(
'user' => $user,
'form' => $form->createView(),
'images' => $images,
));
}
}
At first i was getting this error :
The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) resource. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) resource to an instance of Symfony\Component\HttpFoundation\File\File.
Then i read some posts here and I added 'data_class' => null, where the FileType::class is added to the form.
And from then on I get this error:
The controller must return a response (null given). Did you forget to add a return statement somewhere in your controller?
This is the file that i`m rendering the form to:
useredit.html.twig
{% extends 'base.html.twig' %}
{% block body %}
<h2 class="page-header">EDIT USER {{ user.name }}</h2>
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
{% endblock %}
Ideas?
What if the form is not submitted? You don't return anything, just as the error states.
You could move your return $this->render at the end below the next } so that this is called whether a form is submitted or not.
Or do something custom:
if ($form->isSubmitted() && $form->isValid()) {
....
} else {
// Return something if the form is not submitted
}
The problem is that this condition if ($form->isSubmitted() && $form->isValid()) { is resulting in false and for that reason nothing is returning.
Hope this help you.
You return your twig template only if your form is submitted and valid...
You put your return statement inside if ($form->isSubmitted() && $form->isValid()) { } condition, so method returns null.
return $helpers->json(array(
"status" => "error",
"data" => "Send json with post !!"
));