I want to accomplish the following:
FormType -> If my checkbox is checked, hide a normally required field and make it required = false, so I can submit my Form.
So I need to override a specific form field if my checkbox is checked. Example...
Form:
$builder->add(
'checkbox',
CheckboxType::class,
[
'label' => 'checkbox',
'required' => false,
'mapped' => false,
'attr' => [
'class' => 'checkbox',
]
]
);
index:
$('.checkbox').change(function () {
if ($('.checkbox').is(':checked')) {
$(".end-date").hide();
} else {
$(".end-date").show();
}
});
how do i continue?
i tried something like this (somehow it's not working):
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$form = $event->getForm();
$config = $form->get('what_ever_field')->getConfig();
$options = $config->getOptions();
$form->add(
'what_ever_field',
get_class($config->getType()->getInnerType()),
array_replace(
$options,
[
'required' => false,
]
)
);
});
But it makes no sense because the checkbox and the listener have no relation.
I think it would be much easier to dynamically change the field's required attribute via JS after it's rendered on the page. You're half way there:
JS
$('.checkbox').change(function() {
if ($('.checkbox').is(':checked')) {
$(".end-date").removeAttr("required");
$(".end-date").hide();
} else {
$(".end-date").attr("required","required");
$(".end-date").show();
}
});
This JQuery code can be optimized, but that's about it. Hope it helped.
Related
I create 2 forms not linked to any entity in the same controller.
Each form have it owns submitted button.
I never goes to the submitted function of the second form.
I think it is because the 2 forms have same default name 'form'.
The problem is how to change the form name?
Below what I did
public function index(Request $request)
{
$form1 = $this->createFormBuilder()
->add('sn', TextType::class, [
'required' => false,
])
->add('search', SubmitType::class, ['label' => 'Search'])
->getform();
$form1->handleRequest($request);
if ($form1->isSubmitted() && $form1->isValid()) {
//Do something
}
$form2 = $this->createFormBuilder();
$form2->add('Agree', CheckboxType::class, [
'label' => 'Agree',
'required' => false,
]);
$form2->add('detail', SubmitType::class, ['label' => 'Detail']);
$form2 = $form2->getForm();
$form2->handleRequest($request);
if ($form2->isSubmitted() && $form2->isValid()) {
//Do something else
}
return $this->render('search/index.html.twig', [
'form1' => $form1->createView(),
'form2' => $form2->createView(),
]);
}
If you want to modify the form name, use the createNamed() method:
$form1 = $this
->get('form.factory')
->createNamed('my_name', TextType::class, $task);
You can even suppress the name completely by setting it to an empty string.
How to get field value in form builder in Symfony.
I have 2 Dropdowns in the form
I want to should the related option in Dropdown2 based on Dropdown1 in when the Page is Opening.
Here is My Form
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\Event\DataEvent;
use C2Educate\ToolsBundle\Entity\Students;
public function buildForm(FormBuilder $builder, array $options) {
Field 1:
$builder->add('leadSource', 'entity', array(
'label' => 'How did you hear about C2? Source ',
'class' => 'C2EducateToolsBundle:LeadSources',
'query_builder' => function($repo) {
return $repo->createQueryBuilder('p')->orderBy('p.sort_order', 'ASC');
},
'property' => 'name',
'empty_value' => 'Select'
));
$leadSource = 1;
$leadSource = 1; - it works when I assign value statically, but I want to get the value of "leadSource" and assign it to $leadSource
I want to get the leadSource and pass it to leadSourceSub query
Field 2:
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (DataEvent $event) {
$form = $event->getForm();
$entity = $event->getData();
$leadSource = $entity->getLeadSourceID();
$form->add('leadSourceSub', 'C2Educate\ToolsBundle\Entity\Students', array(
'label' => ' Source Detail ',
'required' => true,
'class' => 'C2EducateToolsBundle:LeadSourceSubs',
'query_builder' => function($repo) use ($leadSource) {
return $repo->createQueryBuilder('p')
->where('p.lead_source_id =:leadSource')
->setParameter('leadSource', $leadSource)
->orderBy('p.sort_order', 'ASC');
},
'property' => 'name',
'empty_value' => 'Select'
));
});
You cannot get form data from $builder, because... it's a form builder, not a form. It doesn't contain any data yet.
To make this work you need to make use of FormEvents. In this case, you probably will need FormEvents::PRE_SET_DATA event listener.
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
// in your case it's C2EducateToolsBundle:LeadSourceSubs
$entity = $event->getData();
$leadSource = $entity->getLeadSource();
// adding this field again will override it.
$form->add('leadSourceSub', 'entity', array(
'label' => ' Source Detail ',
'required' => true,
'class' => 'C2EducateToolsBundle:LeadSourceSubs',
'query_builder' => function($repo) use ($leadSource) {
return $repo->createQueryBuilder('p')
->where('p.lead_source_id =:leadSource')
->setParameter('leadSource', $leadSource)
->orderBy('p.sort_order', 'ASC');
},
'property' => 'name',
'empty_value' => 'Select'
));
}
});
Please note that this code is not tested and may need some validation like to check if $entity is what you expect it to be in any case.
In Symfony I have this part of my code where I am building a view with some data and a form with some radio buttons. When submitting the form I am doing a dump in the view to check which data has been submitted, but the data does not match with the one the form was build. Can someone help? Thanks.
public function playAction(Request $request){
$data = $this->getDbQuestion();
$questionData = $data[0];
dump($questionData);
$answerData = $data[1];
dump($answerData);
$form = $this->createFormBuilder($answerData)
->add('answers', ChoiceType::class,
array(
'choices'=> $answerData,
'multiple'=>false,'expanded'=>true,
'choice_label' => 'answer',
))
->add('Submit',SubmitType::class, array('label' => 'Send Answer'))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted()) {
$formData = $form->getData();
return $this->render('QuizViews/correctAnswer.html.twig', array(
'ss' => $formData
));
}
return $this->render('QuizViews/playQuiz.html.twig', array(
'form' => $form->createView(),
'question' => $questionData
));
}
Twig
<a href="/quiz/question">
<input type="button" value="Start Quiz" />
</a>
<br>
FormData Correct {{ dump(ss) }}
After chatting, this might be a better solution for the answer section:
->add('answers', EntityType::class, array(
'class' => 'AppBundle:Answer',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('a')
->where('a.question_id->getId() = :qID')
->setParameter('qID', 1);
},
'multiple'=>false,
'expanded'=>true,
'choice_label' => 'answer',
))
Try it!
Your call to get the data after verifying the form isSubmitted is incorrect. You need to call like so:
$formData = $form->get('answers')->getData();
That just gets the 'answers' only.
Edit #2
You might also want to change this:
->add('answers', ChoiceType::class,
array(
'choices'=> $answerData,
'multiple'=>false,
'expanded'=>true,
'choice_label' => 'answer',
'choice_value' => $answerData,
))
Which sets the 'choice_value', what is actually selected and returned from the getData().
Can you post your twig answers file please? Edit your post and so I can see.
I am trying to set up an edit form for an entity (Place) in my app. For this purpose I have written the form (PlaceForm), fieldset (PlaceFieldset), .phtml pages and functions in the controller. Since I am new in zf2, I have concentrated on the tutorlias on their homepage. I have seen that from validation is provided by the framework but in my case it is not necessary. None of the fields added in the fieldset have not the required attribute, however when I submit the form under all empty fields I get the message "Value is required and can't be empty" although it is actually not required. I do not want to create a wall of code in this question, so I will start with the function from the controller. If there is someone who would like to help me with this issue, just let me know and I will update any other part of the code (form, fieldset etc.) Thx in advance.
...
public function editPlaceAction() {
$id = $this->params()->fromRoute('id');
$uiServiceProvider = $this->getServiceLocator()->get('FamilyTree\Service\UiServiceProvider');
$placeArray = $uiServiceProvider->fetchSinglePlaceById($id);
$place = new Places($placeArray);
$form = new PlaceForm();
$form->bind($place);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
var_dump($place);
}
}
$view = new ViewModel(array(
'form' => $form,
'title'=>"Edit place"
));
$view->setTemplate("family-tree/family-tree-maintenance/editPlace");
return $view;
}
...
and here you can see how my Fieldset looks like
<?php
namespace Places\Form;
use Zend\Form\Fieldset;
class PlaceFieldset extends Fieldset {
public function __construct() {
parent::__construct('place');
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'name',
'type' => 'Text',
'options' => array(
'label' => 'Name',
),
));
$this->add(array(
'name' => 'admUnit1',
'type' => 'Text',
'options' => array(
'label' => 'AdmUnit1',
),
));
}
}
I have a many-to-many relationship between two entities A and B.
So when adding a form, in order to add entityA to entityB, I am doing the following:
$builder
->add('entityAs', 'entity', array(
'class' => 'xxxBundle:EntityA',
'property' => 'name',
'multiple' => true,
));}
And everything is alright.
But depending on the field type of entityA, I want to sometimes set 'multiple' to false, so I'm doing the following :
if($type=='a'){
$builder
->add('entityAs', 'entity', array(
'class' => 'xxxBundle:entityA',
'property' => 'name',
'multiple' => true,
));}
else {
$builder
->add('entityAs', 'entity', array(
'class' => 'xxxBundle:entityA',
'property' => 'name',
'multiple' => false,
));
}
This gives me the following error:
Catchable Fatal Error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be an array, object given, called in C:\wamp\www\Symfony\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php on line 519 and defined in C:\wamp\www\Symfony\vendor\doctrine\common\lib\Doctrine\Common\Collections\ArrayCollection.php line 48
Can anybody help me?
In EntityA, you have something like this, right?
public function setEntitiesB($data)
{
$this->entitiesB = $data ;
}
Now because you can also receive single value instead of array of values, you need something like this:
public function setEntitiesB($data)
{
if ( is_array($data) ) {
$this->entitiesB = $data ;
} else {
$this->entitiesB->clear() ;
$this->entitiesB->add($data) ;
}
}
i would check the entityA value in the controller and depending on it create different forms.
in controller:
if ($entityA->getType() == 'a') {
$form = new FormB(); // form with multiple true
} else {
$form = new FormA(); // form with multiple false
}