I have a form made in Twig and I want to pass the values of this form to my database, so how do I pass the Twig values to the controller?
In the first photo is the form that I created in twig
Formulario twing
In the second picture is the controller (the entities, and the connection with the database with doctrine orm is complete too), it is only necessary to know how to take the form data and to pass to the controller
Controller
When form submits you will get a POST request to the same URL that it was built in.
Stick to this tutorial:
http://symfony.com/doc/current/forms.html
If you create a form with html and not symfony form you must manually handle form and other step.
you must submit your form to you controller route that seems is cadastrarAction().
Don't forget to declare route with POST method for cadastrarAction().
In controller you can access posted data from request argument like this.
use Symfony\Component\HttpFoundation\Request;
class FooController extends Controller {
cadastrarAction(Request $request)
{
// Find what you exactly want. if you want to get query use this
$request->getQueryString()
}
}
This is bad practice that declare form manually. you must use FormType for easily handle and persist form to database. use symfony official site for more information about form and entity.
In official documentation you can find flow, how create entity, form, twig template and set data in database.
If you need get data from form use this:
if ($form->isSubmitted() && $form->isValid()) {
// -------- Hear you take data --------
$ideda = $form->get('ideda')->getData();
$email = $form->get('email')->getData();
$telemovel = $form->get('telemovel')->getData();
// ---------- Hear you set data's ---------
$usuario -> setIdeda($ideda);
$usuario -> setEmail ($email );
$usuario -> setTelemovel($telemovel);
}):
Related
For example I have edit profile page which have a form for editing the summary. the file's name is Index.tpl.
In form I have a text field, I have added the saveSummary() in the controller i.e. controller.php. How can I invoke the given function on clicking on submit button of form.
Answering directly to your question, you should submit the form to /save-summary/ action if it's called saveSummary() in your controller. Of course don't forget to include prefix of the route.
Generally your approach is not correct because you're trying to use different actions for displaying content and processing the form – you can easily do both operations in one action. Check for isPost() and getPost() in other controllers – this methods are used to divide parts of action responsible for simply getting and displaying content and for processing form data.
You can access controller functions by using action handle at the end of function name ex -
class Mymodule_MytestController extends Core_Controller_Action_Standard{
public function saveSummaryAction(){
.......
}
}
I am new to Laravel and am stuck. I've use the Hugo Firth api wrapper in Laravel for mailchimp. What I can't figure out is where to put this the code in laravel. Does it go on the controller? This is the code for subscribe:
MailChimpWrapper::lists()->subscribe($list_id, array('email' => $email_address));
I know how to make a form inline in php and html, but I want to be able to use the mailchimp API through the route.
You can use this in a controller, for example:
class SubscribeerController extends BaseController {
public function emailSubscribe($list_id)
{
$email_address = Input::get('email_address'); // from the form input
MailChimpWrapper::lists()
->subscribe($list_id, array('email' => $email_address));
}
}
Then use this to declare a route:
Route::post('subscribe/{list_id}', 'SubscribeerController#emailSubscribe');
Then the URI could be something like this:
// 10 assumed the list_id for example
http://domain.com/subscribe/10
if you want to send the $list_id using a form field then you don't need to use {list_id} in the route and also don't need to pass it with the URI, instead you may retrieve it using:
Input::get('list_id'); // Assumed list_id is the form's input name
In this case emailSubscribe($list_id) should be emailSubscribe() as well (When not using {list_id} in route and URI is http://domain.com/subscribe).
I have 10 forms in a single page (they are in tabbed pages).
My controller function is massive, in an effort to make the forms modular, I was planning to just show the forms in my controller function and do the POST to their correspondent controller.
Some of these 10 forms are used in other pages, so by changing the action url, it makes it easier to manage them all in separate controllers.
But then, how am I going to show the form errors and prevent the form to reset if it was invalid?
I could achieve this if embedded controllers could redirect. Am I missing another option?
Symfony2 has to have a reason not to allow redirects in embedded controllers, but I wonder why.
Third edit:
Images of the actual forms: http://imgur.com/sIx3sgs,tnZkvqM,ZAP950s,hk45oTW#0
Image 1: Step1 (can only be created once)
Image 2: Step5 (can be created multiple times) You can see the create form and the edit form
Image 3: Step5 ui forms are slided up.
Image 4: Step6 same as Step1
These forms are not required to go in order, the user can create and save step6 without ever needing to create step1.
Second edit:
This isn't a multiple step form. I named them Step1, Step2, etc. for convenience.
Edit:
This is what I have:
class DefaultController extends Controller{
public function processAction(){
$request = $this->getRequest();
/*** FORM 1 ****/
$entity = new Step1();
$form1 = $this->createForm(new Step1Type(), $entity);
if ($request->getMethod() == 'POST'){
$form1->bindRequest($request);
if($form1->isValid()){
return $this->redirect($this->generateUrl('some_link'));
}
}
/***/
//Do the same for other forms
return array(
'form1' => $form1->createView()
//[...to form10]
);
}
}
This is what I would like to have: (I would do it with embedded controllers but you can't redirect)
class DefaultController extends Controller{
public function processAction(){
$request = $this->getRequest();
/*** FORM 1 ****/
$entity = new Step1();
$form1 = $this->createForm(new Step1Type(), $entity);
//change $form1 action url to point to Step1Controller->createAction()
/***/
//Do the same for other forms
return array(
'form1' => $form1->createView()
//[...to form10]
);
}
}
class Step1Controller extends Controller{
public function createAction(){
$request = $this->getRequest();
$entity = new Step1();
$form = $this->createForm(new Step1Type(), $entity);
$form->bindRequest($request);
if($form->isValid()){
//save entity
return $this->redirect($this->generateUrl($getRedirectLinkFromForm));
}
return $this->redirect($this->generateUrl('some_other_link'));
}
}
I came up with 4 solutions that I could think of, in order from best to worst:
AJAX
No redirect in embedded controllers
Save in session posted data / form errors in case form is not valid
Modify Symfony2 internals to allow redirect from an embedded controller
AJAX
This is actually the best as it reduces whole page requests and it's highly modular.
You would render all 10 embedded controllers but each submit button will instead do an ajax post pointed to the correspondant controller, which will only process the correspondent forms and it will only return the view of that specific form.
And you don't need to get fancy on your javascript, as you only need to make the AJAX call when submit is clicked and load the response to the div where the form is.
No redirect in embedded controllers
The problem with this is that if the user presses F5, it will resend the POST data.
Save in session posted data / form errors in case form is not valid
and Modify Symfony2 internals to allow redirect from an embedded controller
These 2 options are less desirable as it creates complexity.
I'm developing a web application with Zend Framework 1.12, which is something new to me, and I'm not sure about the way to do something I want to.
EDIT: When I talk about Module, I mean Controller, sorry for that, I still mistake the terms ...
On my home page, the module Index, I made what I wanted to do with it, created several actions and all the stuff, but I'd like to add a search engine I'll make myself.
The problem is that I'd like to create the search engine as a separate module named Search, for example, but put the SearchForm in the home page. Hitting submit would send the datas from the form to the Search module.
I don't quite understand how to do that without having to go to /search to access my form and every associated actions.
Do I have to use a View Helper ?
Also, the searchForm in the front page would be some sort of QuicKSearch and accessing /search would show a more elaborated form for the research.
Can someone explain me how to access the searchForm from the Index module or redirect me to the part of the documentation talking about that ? My research are unsuccessful and Google doesn't help me either.
EDIT: When I talk about Module, I mean Controller, sorry for that, I still mistake the terms ...
First of all, build the searchform as viewHelper, then you can reuse it in several views.
The action attribute in form snippet set to searchModule/controller/action.
Additionaly make research about viewHelpers and Forms in Zend Documentation.
I actually prefer to do this as a an action helper and then just use a standard placeholder view helper to present the search form.
let me demonstrate:
the actual action helper just initiates a form and prepares it for display. I'll leave the form structure to you.
//the action helper
//Just fill in the args for the form to be displayed
class NameSpace_Controller_Action_Helper_Search extends Zend_Controller_Action_Helper_Abstract
{
public function direct($action, $label = null, $placeHolder = null)
{
$form = new Application_Form_Search();
//set the action
$form->setAction($action);
//set the submit button text
$form->search->setLabel($label);
//set the hint text displayed in the form window
$form->query->setAttribs(array('placeholder' => $placeHolder,
'size' => 27,
));
return $form;
}
}
I put the helper in the predispatch method of the controller so that each action in the controller can use the search form with having to build it in every page.
//to use the helper in your controller
class IndexController extends Zend_Controller_Action
{
public function preDispatch()
{
//setup action helper and assign it to a placeholder
$this->_helper->layout()->search = $this->_helper->search(
'/index/display', 'Search Collection!', 'Title');
}
//in your view script
<?php echo $this->layout()->search ?>
I like to put the placeholder in my master layout.phtml so that any time I populate the placeholder it will display. Now all you have to do is style it however you want.
Remember: As with any html form the action parameter is just a url so any valid url can be assigned to the form action. In this example I used the /controller/action parameters, but there are many other ways to pass a url to the form. The url helper comes to mind as good way to do it.
url($urlOptions, $name, $reset, $encode): Creates a URL string based
on a named route. $urlOptions should be an associative array of
key/value pairs used by the particular route.
Background: I'm using Symfony Forms and Symfony Validation components to render a form in my applications registration page in my Silex application.
I have the form working correctly, rendering, client side validation and binding data to my entities. I've added a validation method to the entity which correctly validates the entity and produces the expected errors.
Question: I now want to get the errors out of the returned ConstraintValidationList and back into the form to display them on the front end using the twig {{ form_errors }} view helper.
I've consulted the API docs at: http://api.symfony.com/2.0/Symfony/Component/Form/Form.html and can't see the correct method for doing this. Does anyone know how to achieve what I'm looking for?
Here is the code from my Silex controller closure:
$app->post('/register-handler', function(Request $request) use($app)
{
// Empty domain object
$user = new MppInt\Entity\User();
// Create the form, passing in a new form object and the empty domain object
$form = $app['form.factory']->create(new MppInt\Form\Type\RegisterType(), $user);
// Bind the request data to the form which puts it into the underlying domain object
$form->bindRequest($request);
// Validate the domain object using a set of validators.
// $violations is a ConstraintValidationList
$violations = $app['validator']->validate($user);
// Missing step - How do I get a ConstraintValidationList back into the
// form to render the errors in the twig template using the {{ form_errors() }}
// Helper.
});
At the bind request stage validators should be run on the data so you shouldn't need to use the validation service yourself. (Coming from Sf2 rather than Silex the validator service is associated with Form I don't know if you have to do this manually for Silex)
Unless error bubbling is enabled on each field the errors will be held in the fields (children) of the form for displaying errors using {{ form_errors() }}
Although if you really need to get a constraintViolationList into a form errors, you can convert them into Symfony\Component\Form\FormError objects and add them to the form with $form->addError(FormError $formError);