Symfony form entity with allow add - php

I'm building an application with Symfony 2.3.
I have a Booking entity witch is related to a Customer entity by a ManyToOne relation.
In my form, i would like to be able to select one existing customer or create a new one.
For exemple by having a "new customer" option in my customer select who will display the customer form with javascript for exemple.
In fact i'm trying to build an Entity form field with an "allow_add" option like in the collection form field.
Any idea of how i can do that ?
Thank you very much.

Thanks for contributing. I found a way to achieve it !
The solution is to have one field with the Customer form, it has to be mapped, and an entity field en the Customer entity but not mapped.
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event) use ($company) {
$form = $event->getForm();
$data = $event->getData();
$form->add('customer_list', 'entity',
[
'class' => 'SomeBunlde\Entity\Customer',
'label' => 'Client',
'property' => 'fullName',
'expanded' => false,
'multiple' => false,
'mapped' => false,
'query_builder' => function(EntityRepository $er) use ($company)
{
return $er->getByCompanyQueryBuilder($company);
},
]
)
;
if ($data->getCustomer() === null) {
$form->add('customer', new CustomerType());
}
}
After i add an extra option to the Entity form field overloading the finishView method :
public function finishView(FormView $view, FormInterface $form, array $options)
{
array_unshift($view->children['customer_list']->vars['choices'], new SfFormExt\ChoiceView('test', 'new', 'Nouveau client'));
}
Then i add two event listeners, a pre_submit to delete the mapped embeded customer form and its data :
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function(FormEvent $event) use ($em) {
$data = $event->getData();
if ($data['customer_list'] !== 'new') {
unset($data['customer']);
$event->getForm()->remove('customer');
// setting data w/out customer to avoid extra-field error
$event->setData($data);
}
}
);
and a bind event to attach the existing customer to the booking :
$builder->addEventListener(
FormEvents::BIND,
function(FormEvent $event) use ($em) {
$form = $event->getForm();
$data = $event->getData();
if (!$form->has('customer')) {
$existing_customer = $form->get('customer_list')->getData();
if ($existing_customer instanceof Customer) {
$data->setCustomer($existing_customer);
}
}
}
);
I know it may not be state of the art code but it works pretty well.
Edit : I had an issue with this technique because when the customer_list is set to new, it throws an error. I didn't find a way to avoid this error (If you have any idea of how i can achieve this !) so i decided to modify the pre_submit to set to '' the data of customer_list value if we are in the new customer case, then i detect, in the controller, if there is a form validation error on the new client form in order to correctly display it.

I think the best way to do that is managing this workflow with javascript.
If you user choose to create a new customer, you open a create new customer form in a modal and via Ajax create the new customer. The response of the create action returns the id in the response which will be used by you to create the booking with the newly created customer.
The trick is: you will always create a booking from an existing customer. Your user can create a new customer in the process, but in fact it'll be created before you create the booking record.

Related

Symfony 3.4 Ajax in Form event

In my project, the form allow user select a Map in a SelectBox. When Map Selectbox change, the options in GroupLayer Selectbox also change depend on which Map is selected. I see exactly Symfony document for my case in: How to Dynamically Modify Forms Using Form Events
Howerver, in example code:
$formModifier = function (FormInterface $form, Sport $sport = null) {
$positions = null === $sport ? array() : $sport->getAvailablePositions();
$form->add('position', EntityType::class, array(
'class' => 'App\Entity\Position',
'placeholder' => '',
'choices' => $positions,
));
};
I don't know where the getAvailablePositions() function should be and what is the returning of this function?. I think this function will be placed in Sport Entity. Is that right, in Sport Entity, could I query the Position Entity with Doctrine ORM queryBuilder?
with this formModifier you only change the fields that your form have. I don't know where you have the relation between Map and GroupLayer, but this relation is what you need to search. For example, if you have a OneToMany relation beetween the entities you can do:
$map->getGroupLayers();
this was the choices for the selector.
In the other hand you can use a custom method from the GroupLayer repository with the map as parameter or a service that search for the related GroupLayers from a map, it's up to you and your architecture.
Edit #1
With your new info i guess that your code seem near like this:
$formModifier = function (FormInterface $form, Map $map = null) {
$groupLayers = null === $map ? array() : $map->getGroupLayers();
$form->add('position', EntityType::class, array(
'class' => 'App\Entity\GroupLayer',
'placeholder' => '',
'choices' => $groupLayers,
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
// this would be your entity, i.e. SportMeetup
$data = $event->getData();
$formModifier($event->getForm(), $data->getMap());
}
);
$builder->get('sport')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$map = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $map);
}
);
I hope this can help you

Symfony2: init EntityType field with empty data

I have a field (EntityType => select in the view) in my FormBuilder that I want it to be in initialized with empty data so I can fill it after that in the view via ajax.
So I have read symfony's documentation about EntityType and I found the choices attribute that receives an array of data, so I gave it an empty one 'choices' => array() and it did the trick.
Now the problem is when I submit the form, symfony don't know anymore the type of the field and give me null.
This is the builder:
$buidler->add('supplier', EntityType::class, array(
'class' => 'SBC\TiersBundle\Entity\Supplier',
'attr' => array(
'class' => 'uk-select uk-select-supplier'
),
'choices' => array(),
))
As you can see the the type of the field is SBC\TiersBundle\Entity\Supplier but after submit symfony gives me null !
What should I do to achieve my goal?
All right, this is the solution:
First, I need to pass the EntityManager to my form, and to do this I have created a service:
services:
payment.supplier.form:
class: SBC\PaymentBundle\Form\PaymentSupplierType
tags:
- { name: form.type, alias: form_em }
arguments: ["#doctrine.orm.entity_manager"]
Then call the EntityManager in the __construct function:
private $em;
private $supplier;
function __construct(EntityManager $em)
{
$this->em = $em;
}
Second, I need to add two events to the form:
PRE_SUBMIT (to get supplier's code and create Supplier object using the EntityManager):
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function(FormEvent $event){
$data = $event->getData();
$code = $data['supplier'];
$this->supplier = $this->em->getRepository('TiersBundle:Supplier')->find($code);
}
);
And finally, use the POST_SUBMIT event to set the supplier object in the submitted data:
$builder->addEventListener(
FormEvents::POST_SUBMIT,
function(FormEvent $event){
$object = $event->getData();
$object->setSupplier($this->supplier);
$event->setData($object);
}
);
Thanx to Виталий Бойко who gave me a hint about the form events.
So this is what I did with my knowledge and if you have a better solution please share it with us.
Symfony by default use security for forms, so if you didn't have choices in form builder, you can't pass custom choices to the form after render only via javascript, because you get not valid form. You need to create eventlistener for the form. Check this link for more informationenter link description here, here you can find how to add choices.
P.S. sorry for my English)

symfony2 dynamic submitted form modification

I am dynamically modifying form as shown in official example.
I got this field previous which is being submitted via jQuery auto complete feature as user types it. When match is set correctly form should auto update itself to add new field, according to "previous" field value.
$builder->get('previous')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($formModifier) {
$previous = $event->getForm()->getData();
$formModifier($event->getForm()->getParent(), $previous);
});
$formModifier = function (FormInterface $form, $previous = null) {
if ($previous instanceof AwesomeEntity) {
$form->add('changes', new AwesomeChangesType(), array(
'data' => $previous->getLastComment('changes'),
'label' => false,
'mapped' => false
));
}
};
As you can see in line:
'data' => $previous->getLastComment('changes'),
The data is being set after submit has occurred, but it's not set, as far as I figured out: is that by default the symfony is preventing data modification after POST_SUBMIT event so the data is not set.
I don't know why, but it's probably for some good reason that this behavior is as it is. So the question would be is there any other way of setting data for needed field(s), in this situation without breaking the rules of symfony form logic?

Add a required form field based on submitted data in Symfony2

I have a form with a status select. If a certain status is selected and the form is submitted it should reload and require an additional field.
I have read Dynamic generation for submitted Forms and almost every other post on the internet and about this topic and tried different event combinations (and got different errors) but I still struggle to make this to work correctly.
This is what I have so far:
FormType
private function addProcessAfterField(FormInterface $form)
{
$form->add('processAfterDate', 'date', array('required' => true));
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('status', 'entity', array(
'class' => 'Acme\Bundle\ApplicationBundle\Entity\LeadStatusCode',
'choices' => $this->allowedTypes
));
$builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event){
$form = $event->getForm();
$data = $event->getData();
if ($data->getStatus()->getId() == LeadStatusCode::INTERESTED_LATER) {
$this->addProcessAfterField($form);
}
});
$builder->get('status')->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event){
$data = $event->getData();
if ($data == LeadStatusCode::INTERESTED_LATER && !$event->getForm()->getParent()->getData()->getProcessAfterDate()) {
$this->addProcessAfterField($event->getForm()->getParent());
}
});
$builder->add('comment', 'textarea', array('mapped' => false));
$builder->add('Update', 'submit');
}
Error:
ContextErrorException: Catchable Fatal Error: Argument 1 passed to Proxies\__CG__\Acme\Bundle\ApplicationBundle\Entity\Lead::setProcessAfterDate() must be an instance of DateTime, null given, called in /var/www/application.dev/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php on line 360 and defined in /var/www/application.dev/app/cache/dev/doctrine/orm/Proxies/__CG__AcmeBundleApplicationBundleEntityLead.php line 447
As already mentioned I tried different event combinations, one was almost working but then the date was never persisted to the entity so I added the \DateTime type-hint to the setProcessAfterDate() method. I am not sure if I don`t understand the event system correctly or if the error lies somewhere else.
Well, it might not be the best way to solve it, but to make long story short:
$form->handleRequest($request);
if($form->isValid()) // check if the basic version of the form is ok
{
$form = $this->createForm(new XXXXForm(), $form->getData()); // you recreate the form with the data that was submitted, so you rebuild the form with new data
if($form->isValid())
{
// ok
}
// not ok
}
Then inside buildForm function, you base the "required" attribute value of fields based on what you want:
'required' => $this->getCheckRequired($options)
private function getCheckRequired($options) // checks whether field should be required based on data bound to the form
{
if($options && isset($options['data'])
{
switch $options['data']->getStatus():
// whatever
;
}
return false;
}
As I said, this is not the best solution, and it doesn't fix your approach, but rather proposes a different one, but it does the job

Symfony2 multiple choice is not validating

I'm creating a simple list of shop carts with users and products assigned to it.
My form for new cart looks like this:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('cartName', 'text', array('label' =>'Nazwa koszyka:'))
->add('user', new UserForm(), array('data_class' => 'Zadanie\Bundle\Entity\User', 'label' => false))
->add('products','entity', array('label' => 'Wybierz produkty:', 'class' =>'Zadanie\Bundle\Entity\Product' , 'multiple' => true, 'required' => true))
->add('Zapisz', 'submit');
}
and everything is great except that i can submit the form even without selecting any product.
By far i just added "required" by jquery, but i don't like that. Can somebody explain to me why it is not working properly? :P
EDIT:
Here is the code from controller:
/**
* #Route("/cart/edit/{id}",name="_edit_cart")
* #Template()
*/
public function editAction($id, Request $request)
{
$cart = $this->getDoctrine()->getRepository('ZadanieBundle:Cart')->find($id);
if($cart == null)
{
throw $this->createNotFoundException('Nie znaleziono rekordu');
}
$form = $this->createForm(new CartForm(), $cart);
$form->handleRequest($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$data = $form->getData();
$em->persist($data);
$em->flush();
$this->get('session')->getFlashBag()->set('message', 'Koszyk zaktualizowano.');
return $this->redirect($this->generateUrl('_main_carts'));
}
return array('form' => $form->createView());
}
SECOND EDIT:
i found a SOLUTION, ( don't know if the best, but works :) ) so if anybody encounters that:
You have to create your validation file ( validation.yml for example) under YourBundle/Resources/config, in which you have to put information about properties. In my case it was:
Zadanie\Bundle\Entity\Cart:
properties:
cartname:
- NotBlank: ~
user:
- NotBlank: ~
constraints:
- Callback:
methods:
- [Zadanie\Bundle\Form\MyValidator, isUserValid]
and then i created MyValidator:
namespace Zadanie\Bundle\Form;
use Symfony\Component\Validator\ExecutionContextInterface;
use Zadanie\Bundle\Entity\Cart;
class MyValidator {
public static function isUserValid(Cart $cart, ExecutionContextInterface $context)
{
if(!$cart->getUser()->getName())
$context->addViolationAt('name', 'Proszę podać imię.', array(), null);
if(!$cart->getUser()->getSurname())
$context->addViolationAt('surname', 'Proszę podać nazwisko.', array(), null);
if(count($cart->getProducts()) == 0)
$context->addViolationAt('products', 'Proszę wybrać produkt.', array(), null);
}
}
#Mati, regarding your first question about how the required option works, this option only sets the required attribute in HTML5 so does not do anything server side. From the documentation
As of HTML5, many browsers can natively enforce certain validation
constraints on the client side. The most common validation is
activated by rendering a required attribute on fields that are
required. For browsers that support HTML5, this will result in a
native browser message being displayed if the user tries to submit the
form with that field blank.
Regarding your solution, that will certainly work though you may want to consider relying on the built-in validators. I'm fairly sure the product count constraint can use the built-in Count Collection constraint.

Categories