public function addAction(){
$em = $this -> getDoctrine() -> getEntityManager();
$a = new Button;
$form = $this -> createForm(new ButtonType());
$request = $this->get('request');
$value=0;
if($request->getMethod() == 'POST'){
$form->handleRequest($request);
$value = $form->get('addButton')->isClicked();
echo $value;
if($value =1){
$a ->setTextBox(1)
->setPlainText(1)
->setCheckBox(1)
->setRadio(1)
->setButton(1);
$em ->persist($a);
$em ->flush();
}
}
return $this->render('PagePageBundle:Default:add.html.twig', array( 'form' => $form -> createView(),));
}
I want to fill the database by clicking on a button created in the form (need help)
the method isClicked return a boolean value as described in the doc so you can simply check this (in your code you write a wrong if statement: = instead of ==)
So try this code:
$value = $form->get('addButton')->isClicked();
var_dump($value);
if($value){
$a ->setTextBox(1)
->setPlainText(1)
->setCheckBox(1)
->setRadio(1)
->setButton(1);
$em ->persist($a);
$em ->flush();
}
hope this help
Related
In my project I want to use the object created by my precedent form:
Here is the schema of my database:
My QuizController
public function creation(Request $request){
$quiz = new Quiz();
$user = $this->getUser();
$formQuiz = $this->createForm(QuizType::class, $quiz);
$formQuiz->handleRequest($request);
if ($formQuiz->isSubmitted() && $formQuiz->isValid() ) {
$quiz->setCreatedAt(new DateTimeImmutable());
$quiz->setCreatedBy($user);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($quiz);
$entityManager->flush();
return $this->redirectToRoute('creation_questions');
}
return $this->render('quiz/creation.html.twig', [
'formQuiz' => $formQuiz->createView(),
]);
}
And my QuestionController that must be connected with the quiz form
public function creation_questions(Request $request){
$quiz = ?
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid() ) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
What do I have to write in place of the '?'?
You don't show your routing but you could use paramConverte "magic" from SensioFrameworkExtraBundle and do something like this.
/**
* #Route("/some-route/{id}", name="some_route_name")
*/
public function creation_questions(Request $request, Quiz $quiz)
{
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid()) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
Where the {id} part of /someRoute/{id} is the Quiz Id. Symfony should automagically fetch the Quiz matching that id. Or you can be more explicit about how the param converter should interpret such a value. More info here https://symfony.com/bundles/SensioFrameworkExtraBundle/current/annotations/converters.html
Alternatively, you could pass the quiz id and fetch the quiz manually (less magic but totally legit).
/**
* #Route("/some-route/{id}", name="some_route_name")
*/
public function creation_questions(Request $request, int $id)
{
$entityManager = $this->getDoctrine()->getManager();
$quiz = $entityManager->getRepository(Quiz::class)->find($id);
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid()) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
I am using the FPNTagBundle and I would like to have a text field to add tags to entities that works in the same way as the one on this site.
I can create a new entity with tags no problem by using explode but when I come to edit the entity again, I get something like this in the text field.
Doctrine\Common\Collections\ArrayCollection#0000000062a07bb50000000047044868
Is there a way I can pre populate a text field with the array collection, so that all of the tags appear, separated by a space?
Here's what I currently have in my controller:
public function editpageAction(Request $request, $id = NULL)
{
$em = $this->getDoctrine()->getEntityManager();
$tagManager = $this->get('fpn_tag.tag_manager');
$page = new Page();
if ( ! empty($id))
{
$page = $em->getRepository('ContentBundle:Page')->findOneById($id);
$tagManager->loadTagging($page);
}
$form = $this->createForm(new PageType(), $page);
if ($request->isMethod('POST'))
{
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($page);
$em->flush();
return $this->redirect($this->generateUrl('content_admin_list_sections'));
}
}
return $this->render('ContentBundle:Admin:page.html.twig', array('form' => $form->createView()));
}
Any advice appreciated.
Thanks
This is what the Data transfomers are made for.
How to use Data Transformers
A simple example:
public function transform($tags)
{
$tags = $tags->toArray();
if (count($tags) < 1)
return '';
else
return implode(' ', $tags);
}
public function reverseTransform($string)
{
$tags = new ArrayCollection();
$tagsArray = explode(' ', $string);
if (count($tagsArray) > 0)
$tags = new ArrayCollection($tagsArray);
return $tags;
}
Other modules in the application are updating, besides this one.
Here, I am using a model mapper in attempts to update a row set, as found in http://framework.zend.com/manual/en/learning.quickstart.create-model.html
public function SomeAction()
{
$mapper = new Application_Model_SomeMapper();
$model = new Application_Model_SomeModel(); //getters and setters
// action body
$request = $this->getRequest();
$data = $this->_request->getParams();
$someId = $data['someid'];
$get = $mapper->find($someId, new Application_Model_SomeModel, true); //find the row by id, and return array
/*
instantiating a form object and adding "submit"
*/
$form = new Module_Form_FormName();
$form->setAction("/module/controller/action/params/$someId");
$form->setMethod('post');
$form->setName('some_edit');
$submit = $form->createElement('button', 'submit');
$submit->setAttrib('ignore',true);
$submit->setLabel('Edit Something');
$form->addElement($submit);
if ($this->_request->isPost())
{
if($form->isValid($request->getPost()))
{
$data = $this->_request->getPost();
if(empty($data['some_id' ]))
{
$data['tier_models_id'] = NULL;
}
unset($data['submit']);
$setters = $model->setId($data['id'])
->setField1($data['field_1']);
if ($mapper->save($someId, $setters))
{
$this->_redirect("/index/");
}
}
}
$form->populate($tier);
$this->view->form = $get;
}
Here is an example of the save mapper function, except I've included an additional $id parameter
public function save(Application_Model_Guestbook $guestbook)
{
$data = array(
'email' => $guestbook->getEmail(),
'comment' => $guestbook->getComment(),
'created' => date('Y-m-d H:i:s'),
);
if (null === ($id = $guestbook->getId())) {
unset($data['id']);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('id = ?' => $id)); //not happening, although the 'id' is passed as a param
}
}
Is there something missing?
Try this instead
$where = $this->getDbTable()->getAdapter()->quoteInto('id = ?', $id);
$this->getDbTable()->update($data, $where);
I try this cookbook about embed form:
http://symfony.com/doc/current/cookbook/form/form_collections.html
But the embed foreign key (task_id field in Tag table) is not save, always NULL
Here the complete code: https://gist.github.com/1755140
Do you know why?
Thank
Edit::
My trouble was in process form action. Like the tag form is embed dynamically, so i don't know how many tag(s) i will have. If i add in createAction
$tag1 = new Tag();
$task->addTags($tag1);
only the first embed form was correctly save! How to save the other tags?
public function createAction(Request $request)
{
$task = new Task();
$tag1 = new Tag();
$task->addTags($tag1);
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
Edit2:
My solution which resolve the trouble, what do you think about it? Better?
public function createAction(Request $request)
{
$task = new Task();
$tasks = $request->request->get('task', array());
if (isset($tasks['tags'])) {
$tags = $tasks['tags'];
foreach($tags as $tag) {
$tag = new Tag();
$task->addTags($tag);
}
}
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
Edit3:
A much better alternative (not tested again)
http://www.siteduzero.com/tutoriel-3-523899-creer-des-formulaires-avec-symfony2.html#ss_part_2
public function createAction(Request $request)
{
$task = new Task();
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
foreach($task->getTags() as $tag) {
$em->persist($tag);
}
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
In TaskController on line 29 try to use $task->addTags($tag1); instead of $task->getTags()->add($tag1);
I don't understand. Is this solution wrong?
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
foreach($task->getTags() as $tag) {
$tag->setTask($task);
}
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
It works and it seems simpler.
I want to save some data where part of it is from the user where they submit it through a form and the other part is generated in the actual controller. So something like:
# controller
use Acme\SomeBundle\Entity\Variant;
use Acme\SomeBundle\Form\Type\VariantType;
public function saveAction()
{
$request = $this->getRequest();
// adding the data from user submitted from
$form = $this->createForm(new VariantType());
$form->bindRequest($request);
// how do I add this data to the form object for validation etc
$foo = "Some value from the controller";
$bar = array(1,2,3,4);
/* $form-> ...something... -> setFoo($foo); ?? */
if ($form->isValid()) {
$data = $form->getData();
// my service layer that does the writing to the DB
$myService = $this->get('acme_some.service.variant');
$result = $myService->persist($data);
}
}
How do I get $foo and $bar into the $form object so that I can validate it and persist it?
Here's the general pattern I'm using:
public function createAction(Request $request)
{
$entity = new Entity();
$form = $this->createForm(new EntityType(), $entity);
if ($request->getMethod() == 'POST') {
$foo = "Some value from the controller";
$bar = array(1, 2, 3, 4);
$entity->setFoo($foo);
$entity->setBar($bar);
$form->bindRequest($request);
if ($form->isValid()) {
$this->get('some.service')->save($entity);
// redirect
}
}
// render the template with the form
}
Reading the code for the bind method of the Form class, we can read this:
// Hook to change content of the data bound by the browser
$event = new FilterDataEvent($this, $clientData);
$this->dispatcher->dispatch(FormEvents::BIND_CLIENT_DATA, $event);
$clientData = $event->getData()
So I guess you could use this hook to add your two fields.