Related
use Symfony\Component\Form\Forms;
public function form($slug, Request $request){
$id = $request->request->get('id');
$EntityName = 'App\\Entity\\' . ucwords($slug);
$item = new $EntityName();
$item= $this->getDoctrine()->getRepository($EntityName)->find($id);
$form = $this->createFormBuilder($item);
foreach ($classes->fieldMappings as $fieldMapping) {
$form = $form->add($fieldMapping['fieldName'], TextType::class, array('attr' => array('class' => 'form-control')));
}
$form->add('cancel', ButtonType::class, array('label' => 'Abbrechen','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar close_h')))
->add('save', SubmitType::class, array('label' => 'Speichern','attr' => array('id' => 'submit-my-beautiful-form','class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')))
->getForm();
$form->handleRequest($request);
}
Attempted to call an undefined method named "handleRequest" of class
"Symfony\Component\Form\FormBuilder".
You're calling the method on the wrong object here. Note that you're calling $this->createFormBuilder() which returns a FormBuilder, not a form.
What I would suggest is name the variable like this:
$formBuilder = $this->createFormBuilder($item);
And then, you're not storing the result of the getForm() call on the form builder. You should do this:
foreach (...) {
$formBuilder->add(...);
}
$formBuilder
->add(...)
->add(...)
$form = $formBuilder->getForm();
...and this way you'll get an instance of Form which has the handleRequest() method, and the call to it will produce the result you're expecting.
i have tried various ways, but i cant get form to come back isValid() so i wanted to make sure i have this portion correct first.
<?php
namespace ABC\DeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Route,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Template,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Method,
Symfony\Component\HttpFoundation\Request,
Symfony\Component\HttpKernel\Exception\HttpException,
Symfony\Component\Form\FormBuilderInterface,
Symfony\Component\Form\Forms,
Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension,
Symfony\Component\Form\Extension\Validator\ValidatorExtension,
Symfony\Component\Validator\Validation,
Symfony\Component\Validator\Constraints\Length,
Symfony\Component\Validator\Constraints\NotBlank,
Symfony\Component\Config\Definition\Exception\Exception,
Symfony\Component\HttpFoundation\Response,
ABC\CoreBundle\Controller\CoreController;
class DoSomethingController extends CoreController
{
protected $debug = FALSE;
public function doSomethingAction(Request $request)
{
/**
* build the form here
*
* Either use out custom build form object
* $form = $formFactory->createBuilder('form', $defaultData)
*
* Or alternatively, use the default formBuilder
* $form = $this->createFormBuilder($defaultData)
*/
$validator = Validation::createValidator();
$formFactory = Forms::createFormFactoryBuilder()
->addExtension(new HttpFoundationExtension())
->addExtension(new ValidatorExtension($validator))
->getFormFactory();
$defaultData = array(
'comment' => 'Type your comment here',
'name' => 'Type your name here',
'resources' => '{}',
'warning' => 'Warning, your still in debug mode on your controller.php'
);
//$form = $this->createFormBuilder($defaultData)
$form = $formFactory->createBuilder('form', $defaultData)
->setAction($this->generateUrl('do_something'))
->add("emails", 'text', array(
'label' => "Recipient's email address (separate with a comma)",
'constraints' => array(// constraints here
),
))
->add('comment', 'textarea', array(
'label' => "Leave a comment",
))
->add('name', 'text', array(
'label' => "Your name",
'constraints' => array(// constraints here
),
))
->add('email', 'email', array(
'label' => "Your email address",
'constraints' => array(// constraints here
),
))
->add('copy', 'checkbox', array(
'label' => "Send me a copy",
'required' => false,
))
->add('cancel', 'button', array(
'label' => "Cancel",
'attr' => array('class' => 'btn-branded'),
))
->add('save', 'submit', array(
'label' => "Email Resources",
'attr' => array('class' => 'btn-branded'),
));
//make resources visible by putting them into a text box
$resourceInputType = $this->debug ? 'text' : 'hidden';
$form->add('resources', $resourceInputType, array(
'constraints' => array(// constraints here
),
));
//add a visible warning input box, so we know were on debug, we don't want this released to live on debug.
$this->debug ? ($form = $form->add('warning', 'text')) : null;
$form .= $form->getForm();
//alternatively
//$form->bind($_POST[$form->getName()]);
//$form->handleRequest($request);
//validate
if ($form->isValid()) {
$data = $form->getData();
//run some data checks, then fire it off
$something = $this->DoSomething($data);
return $something;
//$return=array("responseCode"=>200, "data"=>$data);
// $return=json_encode($return); //json encode the array
// return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
}else
{
echo '<pre>';
var_dump('form is coming back as not isValid(), make sure debug is off, heres our errors list:<br>');
var_dump($form->getErrorsAsString());
echo '</pre>';
}
//its not a POST, or POST is invalid, so display the form
return $this->render($this->someTemplate, array(
'form' => $form->createView(),
));
}
}
1) Im a bit confused (oop wise) on the way to pass around this form object during conditional manipulation. Do i need to concatenate it when manipulating it or what does symfony offer to avoid this, or am i just passing the object around wrong? see this example to understand better this question. e.g. $form .= $form->getForm(); How would i properly concatenate this form object during manipulation, like i did when i used the ternary, to convine myself that when i pass this object around, its teh same object, and not a new one.
2) see any other problems that might be causing the breakage?
EDIT #Chausser
this is the latest code, streamlined a bit, that i am working with now using some apparently rare exmples found here http://api.symfony.com/2.5/Symfony/Component/Form/Forms.html. its still not coming back isValid() . Please compare my former, and new usage example of the form object.
<?php
/**
* #param Request $request
* #Route("/do/something", name="do_something", options={"expose"=true})
* #Method({"GET", "POST"})
* #return mixed
*/
public function doSomethingAction(Request $request)
{
$defaultData = array(
'comment' => 'Type your comment here',
'name' => 'Type your name here',
'resources' => '{}',
'warning' => 'Warning, your still in debug mode on your controller.php'
);
$resourceInputType = $this->debug ? 'text' : 'hidden';
$formFactory = Forms::createFormFactory();
$form = $formFactory
->createBuilder()
->setAction($this->generateUrl('do_something'))
->add("emails", 'text', array(
'label' => "Recipient's email address (separate with a comma)",
'constraints' => array(// constraints here
),
))
->add('comment', 'textarea', array(
'label' => "Leave a comment",
))
->add('name', 'text', array(
'label' => "Your name",
'constraints' => array(// constraints here
),
))
->add('email', 'email', array(
'label' => "Your email address",
'constraints' => array(// constraints here
),
))
->add('copy', 'checkbox', array(
'label' => "Send me a copy",
'required' => false,
))
->add('cancel', 'button', array(
'label' => "Cancel",
'attr' => array('class' => 'btn-branded'),
))
->add('save', 'submit', array(
'label' => "Email Resources",
'attr' => array('class' => 'btn-branded'),
))
->add('resources', $resourceInputType, array(
'constraints' => array(// constraints here
),
))
->getForm();
$form->handleRequest($request);
//validate
if ($form->isValid()) {
$data = $form->getData();
//run some data checks, then fire it off
$something = $this->DoSomething($data);
return $something;
//other options for returning
//$return=array("responseCode"=>200, "data"=>$data);
// $return=json_encode($something); //json encode the array
// return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
} else {
echo '<pre>';
var_dump('form is coming back as not isValid(), make sure debug is off, heres our errors list:<br>');
var_dump($form->getErrorsAsString());
echo '</pre>';
}
//its not a POST, or POST is invalid, so display the form
return $this->render($this->someTemplate, array(
'form' => $form->createView(),
));
}
EDIT
so now after my edits to get the form to not try and haldne the request, unless its teh POST request, not the GET request
if($request && $request->getMethod() == 'POST'){
$form->handleRequest($request);
//validate
if ($form->isValid()) {
$data = $form->getData();
//run some data checks, then fire it off
$something = $this->DoSomething($data);
return $something;
//other options for returning
//$return=array("responseCode"=>200, "data"=>$data);
// $return=json_encode($something); //json encode the array
// return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
} else {
echo '<pre>';
var_dump('form is coming back as not isValid(), make sure debug is off, heres our errors list:<br>');
var_dump($form->getErrorsAsString());
echo '</pre>';
}
}
which has led to the controller error mentioned below
Ok, it looks as if the validator extension, when used, was breaking, since the HttpFoundationExtension() wasnt being included. Apparently to use either the validator, or the factory builder (not sure which) it needs this extension as well.
working example, copied from initial example, with working parts added.
<?php
namespace ABC\DeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Route,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Template,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Method,
Symfony\Component\HttpFoundation\Request,
Symfony\Component\HttpKernel\Exception\HttpException,
Symfony\Component\Form\FormBuilderInterface,
Symfony\Component\Form\Forms,
Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension,
Symfony\Component\Form\Extension\Validator\ValidatorExtension,
Symfony\Component\Validator\Validation,
Symfony\Component\Validator\Constraints\Length,
Symfony\Component\Validator\Constraints\NotBlank,
Symfony\Component\Config\Definition\Exception\Exception,
Symfony\Component\HttpFoundation\Response,
ABC\CoreBundle\Controller\CoreController;
class DoSomethingController extends CoreController
{
protected $debug = FALSE;
public function doSomethingAction(Request $request)
{
$validator = Validation::createValidator();
$builder = Forms::createFormFactoryBuilder()
->addExtension(new ValidatorExtension($validator))
->addExtension(new HttpFoundationExtension());
$defaultData = array(
'comment' => 'Type your comment here',
'name' => 'Type your name here',
'resources' => '{}',
'warning' => 'Warning, your still in debug mode on your controller.php'
);
$resourcesInputType = $this->debug ? 'text' : 'hidden';
$form = $builder->getFormFactory()
->createBuilder('form', $defaultData)
->setAction($this->generateUrl('do_something'))
->add("emails", 'text', array(
'label' => "Recipient's email address (separate with a comma)",
'constraints' => array(// constraints here
),
))
->add('comment', 'textarea', array(
'label' => "Leave a comment",
))
->add('name', 'text', array(
'label' => "Your name",
'constraints' => array(// constraints here
),
))
->add('email', 'email', array(
'label' => "Your email address",
'constraints' => array(// constraints here
),
))
->add('copy', 'checkbox', array(
'label' => "Send me a copy",
'required' => false,
))
->add('cancel', 'button', array(
'label' => "Cancel",
'attr' => array('class' => 'btn-branded'),
))
->add('save', 'submit', array(
'label' => "Email Resources",
'attr' => array('class' => 'btn-branded'),
))->add('resources', $resourcesInputType, array(
'constraints' => array( // constraints here
),
))
->getForm()
->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
//run some data checks, then fire it off
$something = $this->DoSomething($data);
return $something;
}
// initial render
return $this->render($this->someTemplate, array(
'form' => $form->createView(),
));
}
}
I have a form whose content is created from a DB.
in my controller i have:
/**
* #Route("/HR/manage/{projectID}", name="hr_manage")
*/
public function manageHRAction(Request $request, $projectID)
{
//here I get all the data from DB and create the form
if ($form->isValid())
{
//here I do all the relevant changes in the DB
return $this->render('HR/show.html.twig', array('hrlist' => $HRsInMyDomain, 'form' => $form->createView(), 'HRs' => $HRsInThisProject, 'project' => $prj, ));
}
return $this->render('HR/show.html.twig', array('hrlist' => $HRsInMyDomain, 'form' => $form->createView(), 'HRs' => $HRsInThisProject, 'project' => $prj, ));
}
It updates the info on the DB properly, but it does not build again the form with updated data. Instead of the return inside the "isValid()" I simply need a refresh on the current page.
I assume it's possible and easy to accomplish, but I failed to find how to do it :/
EDIT - here comes more relevant code:
/**
* #Route("/HR/manage/{projectID}", name="hr_manage")
*/
public function manageHRAction(Request $request, $projectID)
{
$user = $this->container->get('security.context')->getToken()->getUser(); //get current user
$em = $this->getDoctrine()->getManager(); //connect to DB
$prj = $this->getDoctrine()->getRepository('AppBundle:Project')->findOneById($projectID);
[...]
// here comes some code to generate the list of $HRsInThisProject and the list of roles ($rolesListForForm)
[...]
foreach ($HRsInThisProject as $key => $HR)
{
$form->add('roleOf_'.$key, 'choice', array('choices' => $rolesListForForm, 'required' => true, 'data' => $HR['role'], 'label' => false, ));
$form->add('isActive_'.$key, 'choice', array('choices' => [0 => 'Inactive', 1 => 'Active'] , 'required' => true, 'data' => $HR['is_active'], 'label' => false, ));
}
[...]
// here there is some code to get the $HRsInMyDomainForForm
[...]
$form->add('HRid', 'choice', array('choices' => $HRsInMyDomainForForm,'required' => false, 'placeholder' => 'Choose a resource', 'label' => false, ));
$form->add('role', 'choice', array('choices' => $rolesListForForm,'required' => false, 'placeholder' => 'Choose a role', 'label' => false, ));
$form->add('save', 'submit', array('label' => 'Save'));
$form->handleRequest($request);
if ($form->isValid())
{
{
[...] here there is a huge portion of code that determines if I need to generate a new "event" to be stored, or even multiple events as I can change several form fields at once
// If I needed to create the event I persist it (this is inside a foreach)
$em->persist($newHREvent);
}
$em->flush();
return $this->render('HR/show.html.twig', array('projectID' => $prj->getId(), 'hrlist' => $HRsInMyDomain, 'form' => $form->createView(), 'HRs' => $HRsInThisProject, 'project' => $prj, ));
}
return $this->render('HR/show.html.twig', array('projectID' => $prj->getId(), 'hrlist' => $HRsInMyDomain, 'form' => $form->createView(), 'HRs' => $HRsInThisProject, 'project' => $prj, ));
}
I also include a screenshot of the form:
If a user selects to add a new resouce, I need to persist it to DB (and that is done properly) but then I need to see it in the list of available HRs, without the need for the user to reload the page.
More dynamic way would be:
$request = $this->getRequest();
return $this->redirectToRoute($request->get('_route'), $request->query->all());
or simply
return $this->redirect($request->getUri());
I managed to solve it in a simple (and I hope correct) way.
I simply substituted the "render" inside the isValid() with the following:
return $this->redirect($this->generateUrl('hr_manage', array('projectID' => $prj->getId())));
I works, but does anybody foresee problems with this solution?
You have to link the form to the request.
$entity = new Entity();
$form = $this->createFormBuilder($entity)
->add('field1', 'text')
->add('field2', 'date')
->add('save', 'submit', array('label' => 'Submit'))
->getForm();
$form->handleRequest($request); // <= this links the form to the request.
only after that you test $form->isValid() and pass this form when rendering the template. If you already did this and haven't included in the code above please show more code for better help.
Here is the right way to do it. Event though you have $projectId slug, in Action you can pass whole Object, in this case Project. Symfony will take care for the rest (fetching right Project entity for you.
/**
* #Route("/HR/manage/{projectID}", name="hr_manage")
*/
public function manageHRAction(Request $request, Project $project)
{
$form = $this->createForm(new ProjectType(), $project);
$form->handleRequest($request);
// ... your business logic or what ever
//here I get all the data from DB and create the form
if ($form->isValid() && $form->isSubmitted()) {
$em->persist($project);
// no need to flush since entity already exists
// no need to redirect
}
// here $form->createView() will populate fields with data since you have passed Poroject $project to form
return $this->render('HR/show.html.twig', array('hrlist' => $HRsInMyDomain, 'form' => $form->createView(), 'HRs' => $HRsInThisProject, 'project' => $prj, ));
}
Update
According to your edit, you need to use javascript for client-side dom manipulation. Check this link from Symfony official document embedded forms. Here you'll find an example of what you're trying to accomplish.
I'm trying to add values into each element of a collection from a multiple form, but I got this :
Call to a member function getQuestions() on a non-object
What is the correct syntax?
This is my code:
$repository = $this->getDoctrine()->getManager()
->getRepository('***Bundle:Projet');
$projet = $repository->find($projetid);
$formBuilder = $this->createFormBuilder($projet);
$formBuilder->add('questions','collection',array(
'type' => new QuestionType(),
'allow_add' => true,
'allow_delete' => true
));
$form = $formBuilder->getForm();
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$membreid = $this->getUser()->getId();
$questions = $projet->getQuestions();
//I'm gonna do a loop here
$questions[0]->setMembreId($membreid);
$projet->addQuestion($questions[0]);
$em->persist($projet);
$em->flush();
return $this->redirect($this->generateUrl('***_nouveau_projet',array('etape' => 3, 'id' => $projet->getId() )));
}
}
return $this->render('***:nouveau_projet.html.twig',array(
'form' => $form->createView(),
'etape' => $etape,
'projet' => $projetid,
));
The error message you got provides relevant clues about what's going wrong.
getQuestions() is called on a non object.
Make sure $project is an instance of ***Bundle:Projet and that
$repository->find($projetid); is returning a valid object.
Probably that the given $projetid doesn't match any record in your date source.
I have a form in Zend Framework 1. when I click on edit button I want to display values from databases in the form. but I don't know how to do it.
This is my form code:
// Add an email element
$this->addElement('text', 'orgname', array(
'required' => true,
'filters' => array('StringTrim'),
'style' => array('width:220px'),
'decorators'=>Array(
'ViewHelper','Errors'
)
));
This is my controller:
public function editclientcompanyAction()
$form = new Application_Form_Companyform();
$form->addform();
$this->view->form = $form;
$request = $this->getRequest();
$editid=$request->getParam('id');
$edit_show = new Application_Model_Clientcompany;
$showdetails = $edit_show->editclient($editid);
$this->view->assign('datas', $showdetails);
How do I display database vlaues in my Zend Form?
There are two cases.
1) Populating form which has fields same like the database table fields : If you have the form which has same fields like the database fields, then you can populate them easily.
First you need to get the data from the database and then call the Zend_Form populate function passing the data as an associative array, where keys will be same like form fields names and values will be values for the form fields, as below in case of your form.
This will be in your controller
$data = array("orgname" => "Value for the field");
$form = new Application_Form_Companyform();
$form->populate($data);
Now send will automatically populate the form field orgname. You dont need to modify your form or set the value field in the addElement.
*2)Setting field value manually: * The second case is to set the value manually. First you will need to modify your form and add a constructor to it. Also in your form class you will need to create a property (if you have multiple fields, then you can create an array property or multiple properties for each field. This will be all up to you.). And then set the value key in the addElement. Your form should look like this
class Application_Form_Companyform extends Zend_Form
{
private $orgname;
public function __contruct($orgname)
{
$this->orgname = $orgname;
//It is required to call the parent contructor, else the form will not work
parent::__contruct();
}
public function init()
{
$this->addElement('text', 'orgname',
array(
'required' => true,
'filters' => array('StringTrim'),
'style' => array('width:220px'),
'decorators'=>Array('ViewHelper','Errors'),
'value'=>$this->orgname
)
));
} //end of init
} //end of form
Now your controller, you will need to instantiate the form object passing the value of the orgname field like below
$form = new Application_Form_Companyform("This is the value for orgname");
And thats it.
I used such methods and it works like a charm. For your requirements, you may need to adjust the above sample code, as i did not checked it, but it will run fine for sure i hope :P
Thank you
Ok in either ZF1 or ZF2 just do this.
// Add an email element
$this->addElement('text', 'orgname',
array(
'required' => true,
'filters' => array('StringTrim'),
'style' => array('width:220px'),
'decorators' => Array('ViewHelper','Errors'),
'value' => $showdetails->orgname
)
));
You might want to test first for null/empty values first though, you could use ternary operators for convenience:
// Add an email element
$this->addElement('text', 'orgname',
array(
'required' => true,
'filters' => array('StringTrim'),
'style' => array('width:220px'),
'decorators' => Array('ViewHelper','Errors'),
'value' => empty($showdetails->orgname)? null : $showdetails->orgname
)
));
Please have a look in my edit function at /var/www/html/zend1app/application/controllers/CountryController.php :
public function editAction() {
$data = $this->getRequest()->getParams();
$id = (int)$data['id'];
$options = array();
$country = $this->getCountryModel()->fetchRow("id=$id");
if(!$country)
{
throw new Exception("Invalid Request Id!");
}
$form = new Application_Form_Country();
$form->addIdElement();
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())){
$data = new Application_Model_Country();
if($data->save($form->getValues()))
{
$message = array("sucess" => "Country has been updated!");
}
else {
$message = array("danger" => "Country could not be updated!");
}
$this->_helper->FlashMessenger->addMessage($message);
return $this->_helper->redirector('index');
}
}
$options = array (
'id' => $country->id,
'name' => $country->name,
'code' => $country->code
);
$form->populate( $options ); // data binding in the edit form
$this->view->form = $form;
}
and form class at /var/www/html/zend1app/application/forms/Country.php :
class Application_Form_Country extends Zend_Form
{
public function init()
{
// Set the method for the display form to POST
$this->setMethod('post');
// Add an email element
$this->addElement('text', 'name', array(
'label' => 'Enter Country Name:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
// Add the comment element
$this->addElement('text', 'code', array(
'label' => 'Enter Country Code:',
'required' => true,
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Save',
));
// And finally add some CSRF protection
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
}
public function addIdElement()
{
$this->addElement('hidden', 'id');
}
}
HTH