Symfony2: fos_user_bundle embedding registration form with entity - php

I've got 3 entities:
- overriden User
- Address
- Company
User Entity got entity fields Address and Company.
Now I'm trying to build User Registration Form using as well fields from Address and Company entities. The problem is - I have no idea how to proceed with this.
I was trying to do sth like this:
$this->addCommonFields($builder);
$builder
->add('company', 'entity', array(
'label' => 'street',
'class' => 'AcmePsoBundle:Company',
'property' => 'street',
));
but then I receive dropdown list and it supposed to be textfield.
#Edit: Should I use DataTransformer?

You should create new form type for your AcmePsoBundle:Company entity, and use it as:
$builder->add('company', new YourCompanyFormType());
YourCompanyFormType.php example:
class YourCompanyFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add(
'street',
'text'
);
}
And don't forget to set empty Company to new user entity $user->setCompany(new Company()); before form.

Related

Object of class AppBundle\Entity\User could not be converted to string Symfony 3

I'm trying to create a form with EntityType but is not running.
This is my BD:
I already got Users and AcademiucProgram, so I want to create a register between User and AcameicProgram.
From my controller it provides a variable to my form which contains the ID of the user.
My controller:
public function indexAction(Request $request,$id){
$ac = new Usersacademi();
$form = $this->createForm(UsersacademiType::class,$ac,array('id'=>$id));
$form->handleRequest($request);
if($form->isValid()){
$ac->setIdacademicprogram($form->get("idacademicprogram")->getData());
$ac->setIduser($form->get("iduser")->getData());
$em = $this->getDoctrine()->getManager();
$em->persist($ac);
$flush = $em->flush();
}
else{
}
return $this->render("AppBundle:admin:apteacher.html.twig", array(
"form" => $form->createView()
));
}
My Form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('idacademicprogram', EntityType::class, array(
"required"=>"required",
'class' => 'AppBundle:Academicprogram',
'choice_label' => 'name'
))
->add('iduser', EntityType::class, array("required"=>"required",
"data" =>$options["id"],
'class' => 'AppBundle:User',
"attr"=>array(
"class" => "form-iduser form-control"
)))
->add('Registrar',SubmitType::class, array("attr"=>array(
"class" => "form-submit btn btn-success"
)));
}
So I want to be able to select the AcademicProgram with a Select Option (this is actually running) and then on the second field (idUser) I want that by default is the id of the user selected (that id number is provided by the controller) and then be able to submit this register.
Looks like you forgot to add choice_label in your user form field or you can add a __toString() method inside your User entity.
From the docs:
If left blank, the entity object will be cast to a string and so must have a __toString() method.
By default EntityType already uses entity id as value.

Form - Accessing submitted/bound data

Imagine this form
class CarType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('brand', EntityType::class, array(
'class' => 'AppBundle:CarBrand',
'label' => 'Brand',
))
->add('model', EntityType::class, array(
'class' => 'AppBundle:CarModel',
'label' => 'Car model',
'choices' => array(), // <- Depends on brand
));
// ...
}
}
I used some ajax to make the model list depending on brand selection.
I didn't use FormEvents because it was a real pain in the ass for my simple need (I have actually 3 dependencies based on multiple parameters and I already spent an entire day trying to figure out how to make it work with FormEvents)
Now, once the form is submitted, I want to get the bound values from my controller.
/**
* #Route("/context", name="context_selection")
*/
public function carSelectionAction(Request $request)
{
$form = $this->createForm(CarType::class, new Car());
$form->handleRequest($request);
if ($form->isSubmitted()) {
$car = $form->getData();
dump($car); // <- Getting only brand here
}
return $this->render('AppBundle::car-selection.html.twig', array(
'form' => $form->createView()));
}
The dumped data is showing only the CarBrand object bound, I imagine because the selected CarModel is not a valid choice.
How can I get the bound CarModel ?
I'd rather not having to read the request params and load the objects myself

Symfony User Roles not selected in user form

I have created a simple user/role form. The form shows the user's detail correctly and displays all the possible roles, but for some reason it does not pre-select the users' current role. For the relationship between the user and role I had the following in the user entity class:
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users", cascade={"persist","remove"})
* #ORM\JoinTable(name="user_role")
*/
protected $roles;
The formtype class was built using:
$builder->add('firstname')
->add('lastname')
->add('email')
->add('roles');
The database looks like this:
Any hints/assistance would be appreciated.
You need to define your roles fields as entity
http://symfony.com/doc/current/reference/forms/types/entity.html
change this line ->add('roles'); to:
->add('roles', 'entity', array(
'multiple' => true,
'expanded' => true,
'property' => 'name',
'class' => 'Your_Path\Entity\Roles',
));
it should work.
Second option:
you can try to create role type form as mentioned here and then do something like this
$builder->add('roles', 'collection', array('type' => new RoleType()));
its recomended to read this this about mapped option and other as by_reference
Had the same problem in symfony4, adding this did the trick for me:
'choice_value' => function ($choice) {
return $choice;
},

Concatenate properties in Symfony2 buildForm()

I have a set of entities in Doctrine which depends on each other to build certain data, and I need to create a form which uses data from two of those entities.
I have a Magazine entity, an Issue entity and a Chapter entity. The Magazine (Mag1, Mag2) has it's name, the Issue, that belongs to only one Magazine, has it's 'number' (Mag1->Issue 1, Mag1->Issue 2, Mag3-> Issue 1, Mag2 -> Issue 'Summer'). The Chapter have to belong to just one Issue, but when creating the form, to build the Issue selector I need to concatenate properties from two entities:
class ChapterType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('number')
->add('issue', 'entity', array(
'class' => 'Bundle:Issue',
'property' => 'magazine.name'
))
;
}
...
What I need to do is concatenate in the 'property' something like 'magazine.name'+'number' (where 'number' is the Issue which will be added number. Trying to concatenate with the . like in php strings doesn't work since they aren't strings so I don't know what I have to do or if It's possible to do It this way.
In the Issue create a new getter that does the concat. Given that you have properly setup the ManyToOne relationship, the getter should be something like:
public function getMagazzineAndIssue() {
return $this->magazine->getName() . $this->number;
}
in the form, use this new method as the property:
$builder
->add('name')
->add('number')
->add('issue', 'entity', array(
'class' => 'Bundle:Issue',
'property' => 'magazineAndIssue'
))

How to change input types in existing form using Symfony2?

I've got form class where I'm defining some inputs, something liek this:
class User extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('mail', 'text', array('label' => 'Mail'))
->add('password', 'text', array('label' => 'Hasło'))
->add('description', 'textarea', array('label' => 'Opis'));
}
}
I want to change mail and password input type to readonly and set them some values.
Now, I use form this way:
$form = $this->createForm(new User($this->get('database_connection')));
I tried many things, but Symfony2 has so many Form classes and I've lost in that.
I want to simply add some atributes to existing, added inputs.
I don't use Doctrine2 ORM, I use Doctrine DBAL, if it does matter.
Thanks in advance.
your can set default value with 'data' parameter and readonly with attr parameter
$builder
->add('mail', 'text', array('label' => 'Mail', 'data' => 'Default value'
attr => array('readonly=>'readonly')));

Categories