I am wondering how to solve this problem:
I have form with 4 fields. I want 4th field to be dependent on user status (logged or unlogged). For logged user I will get ID from session but unlogged user should provide username manually.
I dont know which option should i use. Inherit_data, two form types (two much duplicated code) or validation groups based on the submitted data. Any ideas?
Ok, There are several ways to achive that.
Take a Look at FormEvents. In your case it would be FormEvents::PRE_SET_DATA and then read about dynamic forms
I personly prefer to do following
public function buildForm(FormBuilderInterface $builder, array $options)
{
//$builder->add( ... )
//$builder->add( ... )
//$builder->add( ... )
//each-event with own method, but of cource it can be a callback like in a tutorial above
$builder->addEventListener(FormEvents::PRE_SET_DATA, array(this, 'onPreSetData');
}
and in the same class there is a method onPreSetData
public function onPreSetData ( FormEvent $formEvent )
{
$form = $formEvent->getForm();
$user = $formEvent->getData();
//pseudo-code
if( $user->isLoggedIn() )
{
$form->add('user', HiddenType::class, array(
));
}
else
{
$form->add('user', TextType::class, array(
'label' => 'Username',
'required' => true,
'constraints' => array(
new NotBlank(array('message' => 'please enter username...')),
// new YourCustomValidator(array('message' => 'not enough minerals...')),
)
));
}
}
I personally think a more elegant solution is to pass the user to the form builder from your controller. It's been covered in this answer here:
how to check the user role inside form builder in Symfony2?
you can create form by individual fields like
{{ form_row(form.username) }}
{{ form_row(form.email) }}
{{ form_row(form.phone) }}
{% if(app.user) %}
//your conditional field
{% endif%}
By this way, you have to create submit button as well as csrf token if there
I hope this will quite helpful :)
Related
so I'm creating an e-commerce website using symfony and twig. Right now The client can enter manually the quantity he wants of a specific product, but i want that quantity to not exceed the stock we have of that product. So for example if we have 5 chairs, i want him to choose between 1 and 5.
For that i created a dropdown :
<div class="field select-box">
<select name="quantity" data-placeholder="Select your quantity">
{% for i in 1..produit.stock %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
</div>
I want to use the selected value to put it inside a form,, or maybe find another way to set the quantity asked without using the form or even just change the way the form looks because right now it only takes input. Should i generate another form ?
Hopefully i was clear.
Here's what my formType looks like :
class ContenuPanierType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('quantite');
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => ContenuPanier::class,
]);
}
}
and here's a bit of code from the controller that creates a cart, add the products and all the information regarding it (quantity, user it belongs to, date)
if(is_null($updateContenuPanier)) {
$contenuPanier = new ContenuPanier();
$contenuPanier->setDate(new Datetime());
$contenuPanier->setPanier($panier);
$contenuPanier->setProduit($produit);
$contenuPanier->setQuantite($request->get("contenu_panier")["quantite"]);
}
This can be done with the ChoiceType. You just need to determine your maximum allowed value and configure the appropriate options.
public function buildForm(FormBuilderInterface $builder, array $options): void
{
// access the entity
$entity = $builder->getData();
// your custom logic to determine the maximum allowed integer value based on $entity
$max = $entity->getStockOnHandMethodName();
$builder->add('quantite', ChoiceType::class, [
'choices' => range(1, $max),
'choice_label' => function ($choice) {
// use the value for the label text
return $choice;
},
// prevent empty placeholder option
'placeholder' => false,
]);
}
I'm almost certain you will still need to verify that the submitted quantity is still valid in your controller action which handles the form submission.
Have a look at Form Input Types here. You can specify the options. This field in particular will vary for each product (Product A = 5 in stock, Product B = 10 in stock).
I doubt a select field is the best here, maybe just use a simple <input type="number">, but that's just my thought on this.
$builder->add('quantite', ChoiceType::class, [
'choices' => [ // instead of this, do a loop to create your options
'Apple' => 1,
'Banana' => 2,
'Durian' => 3,
],
)
```
I have two issues when sending a form with the GET method with Symfony 4. This form contains filters and submitting this form updates the list of displayed items according to the selected filters.
The form is built like this:
class MyForm extends AbstractType {
...
public function buildForm(...) {
$builder
->setMethod("GET")
->add(
"first_filter",
ChoiceType::class,
...
)
->add(
"second_filter",
EntityType::class,
...
)
->add(
"button_apply",
SubmitType::class
);
First problem, after sending the form, the URL looks like this:
/action?my_form[first_filter]=...&my_form[second_filter]=...
Is it normal that the form name is included before every field name, and why the URL could not simply be:
/action?first_filter=...&second_filter=...
The second problem is that the submit button is part of the params visible into the URL:
/action?my_form[button_apply]=&...
As far as I know, the submit button itself should not be a parameter ?
Thanks in advance
it's the normal behaviour, and it can be circumvented, but it requires to call createNamed instead of create on a form factory (see ControllerTrait::createForm) ... so Symfony\Component\Form\FormFactory::createNamed())
// at the top: use Symfony\Component\Form\FormFactory
public function yourControllerAction(FormFactory $formFactory, Request $request) {
$form = $formFactory->createNamed(
'', // form name, otherwise form class name camel_cased
YourFormType::class, // your form type
[], // initial data or object or whatever!
[] // form options
);
// rest of the script is identical, it's still a normal form
}
or you don't inject it and do what the trait does:
$form = $this->container->get('form.factory')->createNamed(
// parameters same as before
);
for the button to disappear from the GET/POST, I would advise you to remove the button from your form and instead add it to your template (also increases reusability).
{{ form_start(form) }}
{{ form_widget(form) }}
<button type="submit">{{ 'your label'|trans }}</button>
{{ form_end(form) }}
which makes the button submit the form, but since it has no name and value it won't add to the data (in contrast to the SubmitType button form type).
I have a form builder which builds a form
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->
add('typeTask',TextType::class,array('label'=>"Вид заявка"))->
add('description',TextareaType::class,array('label'=>"Описание"))->
add('term',DateType::class, array(
'widget' => 'choice',
'label'=>"Краен срок"
))->
add('designer',TextareaType::class,array('label'=>"Дизайнер",
"required"=>false))->
add('executioner',TextareaType::class,array('label'=>"Под изпълнител",
"required"=>false))->
add("file",TextType::class,array('label'=>"Файл",
"required"=>false))->
add("ergent",CheckboxType::class,array('label'=>"Спешно",
"required"=>false))->add("approved",HiddenType::class,array(
"required"=>false
))->add("rejected",HiddenType::class,array(
'required'=>false
));
}
As you see I have 2 fields which are "approved" which can be true or false and rejected which can also be true and false. Usually they are hidden because only 1 type of user can access them - ROLE_ADMIN and the rest is for ROLE_EDITOR. In my case the ADMIN needs to only approve or reject it and the EDITOR can't do that. The biggest issue is that I don't need a whole form, but rather 2 buttons - "Approve" and "Reject" when the Project is shown ("show" action), but the action which changes the Project is "edit" and so what I tried so far is from "show" to send a form to "edit" and then when the edit action is over to load the "show" action again.I tried achieving this by creating 2 forms - approveForm and rejectForm which can hold only 1 property each and send and flush them to "edit" function, but the edit function doesn't accept the form and also if it did it would have deleted everything else. Here is my code so far
In show action -
$projectFormApprove = $this->createForm('AppBundle\Form\ProjectType', $project,array(
"method"=>"post"
));
$projectFormApprove->remove("description");
$projectFormApprove->remove("designer");
$projectFormApprove->remove("executioner");
$projectFormApprove->remove("term");
$projectFormApprove->remove("typeTask");
$projectFormApprove->remove("file");
$projectFormApprove->remove("ergent");
$projectFormApprove->remove("approved");
$projectFormApprove->remove("rejected");
$projectFormApprove->add("approved",HiddenType::class,array(
"data"=>true
));
$projectFormReject = $projectFormApprove;
$projectFormReject->remove("approved");
$projectFormReject->add("rejected",HiddenType::class,array(
'data'=>true
));
This will create 2 forms each having 1 property and here is what happens in my twig template
<tr>
<td>
{{ form_start(approveForm, {'action': path('project_edit', { 'id': project.id })}) }}
{{ form_widget(approveForm) }}
<input type="submit" value="Approve" />
{{ form_end(approveForm) }}
</td>
</tr>
<tr>
<td>
{{ form_start(rejectedForm,{'action': path('project_edit', { 'id': project.id })}) }}
{{ form_widget(rejectedForm) }}
<input type="submit" value="Reject" />
{{ form_end(rejectedForm) }}
</td>
</tr>
I need two forms since there are 2 buttons which simply submit them and no one actually changes the value ( this is the reason why in "show" function the created property have "data"=>true. If the form is submitted it will do it automatically.
Here is what is in my "edit" function -
/** #var $user User */
$user = $this->getUser();
$project = new Project();
$form = $this->createForm('AppBundle\Form\ProjectType', $project);
if($user->getType() != "LittleBoss"){
$form->remove("designer");
$form->remove("executioner");
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$project->setFromUser($user->getUsername());
$project->setDepartment($user->getDepartment());
$project->setIsOver(false);
$project->setDate(new \DateTime());
$project->setSeenByDesigner(false);
$project->setSeenByExecutioner(false);
$project->setSeenByLittleBoss(false);
$project->setSeenByManager(false);
$em = $this->getDoctrine()->getManager();
$em->persist($project);
$em->flush();
return $this->redirectToRoute('project_show', array('id' => $project->getId()));
}
return $this->render('project/new.html.twig', array(
'project' => $project,
'form' => $form->createView(),
));
Now to my actual problem - As you see I first remove "approved" field and then I add new one with predefined value. What I want is to change not the values, but the type of description and the rest fields. Is there a way to say $form->change(); or anything that can change the types of the fields without having to remove them. The type I want them to be is HiddenType and set their data so that when I submit one of the 2 forms it will be accepted as valid in the "edit" action then flushed to the database and everything will be fine. So far when one of the buttons - "Approve" or "Reject" is clicked in the "edit" action $edit_form->IsSubmited() returns false.
I suggest you to create seperate forms, one for editor and another for admin. Then in controller use the form you need by permissions of the logged in user.
if ($this->authorizationChecker->isGranted('ROLE_EDITOR')) {
$form = $this->createForm(EditorType::class);
} elseif ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
$form = $this->createForm(AdminType::class);
}
$form->handleRequest($request);
In both forms you can use same entity, but different fields.
So say I have a Category and a Product entity, where Category has many Product entities. My Category form builder looks like this:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class)
->add('products', CollectionType::class, array(
'entry_type' => ProductType::class,
'allow_add' => true,
'by_reference' => false,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => '__product_prot__'))
->add('save', SubmitType::class))
;
}
And my Product form builder looks like this:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class)
->add('dateAdded', DateType::class)
;
}
What I would like to know is how to set the value of dateAdded so that whenever a new prototype is added, it displays today's date?
Some people have suggested using the Entity __construct() function to create the default, but this doesn't appear to work for prototypes. I've also found the placeholder option, but I'm not sure how to use it so that it always has today's date - i.e this doesn't appear to work:
->add('addDate', DateType::class, array(
'placeholder' => new \DateTime();
))
As the error is: Attempted to call function "DateTime" from the global namespace
Additionally, I've found the prototype_data field in the CollectionType field, but again, I'm not sure how to specify to only put data in a single field, and to make it dynamic.
Can someone tell me the best method to use - and the correct syntax?
Edit:
So my __construct() looks like:
public function __construct()
{
$this->addDate = new \DateTime();
}
Which works fine for the Category entity (if I give it a date field for testing), but not the prototyped Product entity. When I load the prototype into the form, I just get a default date of 1st Jan 2011. The prototype looks like:
{% block _category_products_entry_row %}
<li>
{{ form_row(form.name) }}
{{ form_row(form.dateAdded) }}
</li>
{% endblock %}
Interestingly, I've also found if I load the new form with a Product entity created already in the Category controller, the dateAdded field that appears due to:
{% for product in form.products %}
{{ form_row(product) }}
{% endfor %}
Has today's date as it's default value. This would suggest to me that the loading of the prototypes which is done in the same fashion as the How to Embed a Collection of Forms tutorial - is causing the issue.
To set a default value to a form field, you can use "data" property and use FormEvent to handle form on update. Here is the result:
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class)
->add('dateAdded', DateType::class, array(
'data' => new \DateTime(),
))
;
$builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
$product = $event->getData();
$form = $event->getForm();
if (!$product) {
return;
}
if ($dateAdded = $product->getDateAdded()) {
$form->add('dateAdded', DateType::class, array(
'data' => $dateAdded,
));
}
});
}
On PRE_SET_DATA, you can override the default value on the dateAdded field with the data you fetched.
For more info, you can visit http://symfony.com/doc/current/reference/forms/types/date.html#data and https://symfony.com/doc/current/form/events.html
Hope it helps
For starters, I'm new to symfony2 -> coming from Laravel and ZF1 I have to admit it is not what I expected. I had a lot of struggle with simple tasks and by the moment of writing this twig editing is still a pain.
So scenario:
I have a invoice form with 2 datetime fields in it, I really hate that ugly 3 select field that is generated so I included my jQuery datepicker.
http://tinypic.com/r/eg5kyg/8
For my initial insertion of data because of the datetime I needed to create my form with a input type "text" :
$form=$this->createFormBuilder($invoice)
->add('date_ref','text', array(
'required'=> true))
->add('date_sent','text', array(
'required' => true ))
In this way that ugly 3 select datepicker is not shown and my users can select a date in an elegant way.
All good until the edit form:
I don't know why I didn't managed to get this done as i initially wished :
$invoice = $em->getRepository('AppBundle:Invoice')->find($id);
$form=$this->createFormBuilder($invoice)
->add('date_ref','text', array(
'required'=> true))
->add('date_sent','text', array(
'required' => true ))
->add('value','integer',array('required'=>true))
->add('nr_ref','text',array('required'=>true))
So i wanted to create a form from a entity with his properties but in the view
<div class="form-group">
{{ form_label(theForm.date_ref, 'Date Refferenced', { 'label_attr': {'class': 'control-label col-md-5'} }) }}
{{ form_errors(theForm.date_ref) }}
<div class="col-md-6">
{{ form_widget(theForm.date_ref,{'attr': {'class': 'form-control', 'data-provide':'datepicker'}}) }}
</div>
</div>
Was not working so I couldn't create my Edit Form as my first form with the date_ref input with a "text" value.
I searched and found out that creating a form from a entity data you need to create a "Type" so I created my "InvoiceType"
which has :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('is_paid')
/* not working
->add('date_ref', 'date', array('input' => 'datetime',
'format' => date('y-M-d'),
'widget' => 'single_text'))
*/
->add('date_ref') //this is a datetime obj which results in those 5 selects
->add('date_sent')
->add('value')
->add('nr_ref')
->add('name_provider')
;
}
$invoice = $em->getRepository('AppBundle:Invoice')->find($id);
$form = $this->createForm(new InvoiceType(), $invoice);
But because this method creates a form from the entity, if I change the type from the buildForm() function .. I get an error that he expects a Object of Datetime instead of a string ("text").
So now I am stuck at making the Edit Form .. that would be a type, 1 input Text and pre-populated with the date from the Database(something like 2014/02/02) using datepicker and when you click on it, it should appear as in the create form.
Like I said I am new, I learned a lot of things that I normally done other ways in other MVC and I struggle a lot with this datetime Object and symfonys 3 select datetime.
http://tinypic.com/r/28bz5h4/8
<- This looks awful
Thanks a lot Khalid Junaid, after I looked up the post you have mentioned I finally got it working as i wanted:
Solution:
->add('date_ref', 'date' ,array(
'widget'=> 'single_text',
'format'=>'d/M/y'))
->add('date_sent','date' ,array(
'widget'=> 'single_text',
'format'=>'d/M/y'))