module.config contains form, that is injected into controller
'passwordForm' => function($sm){
$form = new \Application\Form\PasswordForm();
$form->setInputFilter(new \Application\Form\PasswordInputFilter());
return $form;
},
Controller:
if($this->getRequest()->isPost()){
$form->setData($this->getRequest()->getPost());
if($form->isValid()){
//ok
}
}
return array('form' => $form);
However, if the form is not validated, I see empty fields at form view <?=$this->formRow($this->form->get('passwordOld'));?>. If I echo its value, I see it displayed: <?php var_dump($this->form->get('passwordOld')->getValue());?>
How can I make visible values of not validated form? The key point is that the form is not binded to any object.
Password form element is intentionally done in such way for security reasons.
You must never (re)populate form with passwords.
Related
Here is my Form
{{ Form::open(array('url' => 'register', 'class' => 'form-signin')) }}
// form username , password .. fields here
{{ Form::close() }}
And the route is
Route::post('register', 'RegisterController#registeruser');
And the Controller is
public function registeruser()
{
//validation
return Redirect::to('/')->withErrors($validator); // main
}
As, i am being redirected i won't be having any fields that is filled in the form.
I know that i should use request and response for this.
I tried with below response, even this is a horrible try.
return Response::view('home')->header('utf-8', $messages);
But while doing above even the page reloads and the values filled in the form disappears. How can i through the errors without the values disappears ?
Is there a way to have filled the fields in the form as entered ?
You need to use ->withInput()
return Redirect::to('/')->withInput()->withErrors($validator); // main
You can use Input::flash()
public function registeruser()
{
//validation
Input::flash();
return Redirect::to('/')->withErrors($validator); // main
}
Then in the controller method that handles the redirect you can access the old input with Input::old(). Using Input::all() will only return data for the current request.
You can also use the ->withInput() chained method on your return line.
Read more about it here http://laravel.com/docs/4.2/requests
Let's suppose you have a validation like this:
$validation = Validator::make($input, $rules);
Then you need to do that:
if( $validation->fails() )
{
return Redirect::back()->withInput()->withErrors($validator->messages());
}
note the Redirect::back() that allows you to get back to your form and fill it automatically with user input
I need a help..
I have a unique form with multiples fieldsets, and i need separate some fieldsets in tabs..
So, i tried in the view (form is my variable with the whole form):
$form = $this->form;
$customFieldset = $form->get('customFieldset');
$form->remove('customFieldset');
It works, my fieldset form is in $customFieldset.. but, i can't render this!
When a try:
echo $this->form($customFieldset);
//OR
echo $this->formInput($customFieldset);
//OR
$this->formCollection($customFieldset);
None of that works..
I'm doing right? How i can do it?
Thank very much.
To achieve the result you want (using the form across several tabs, it is better to construct the form differently, based on the tab's number. For example, your form constructor method would look like below:
<?php
namespace Application\Form;
use Zend\Form\Form;
// A form model
class YourForm extends Form
{
// Constructor.
public function __construct($tabNum)
{
// Define form name
parent::__construct('contact-form');
// Set POST method for this form
$this->setAttribute('method', 'post');
// Create the form fields here ...
if($tabNum==1) {
// Add fields for the first tab
} else if($tabNum==2) {
// Add fields for the second tab
}
}
}
In the example above, you pass the $tabNum parameter to form model's constructor, and the constructor method creates a different set of fields based on its value.
In your controller's action, you use the form model as below:
<?php
namespace Application\Controller;
use Application\Form\ContactForm;
// ...
class IndexController extends AbstractActionController {
// This action displays the form
public function someAction() {
// Get tab number from POST
$tabNum = $this->params()->fromPost('tab_num', 1);
// Create the form
$form = new YourForm($tabNum);
// Check if user has submitted the form
if($this->getRequest()->isPost()) {
// Fill in the form with POST data
$data = $this->params()->fromPost();
$form->setData($data);
// Validate form
if($form->isValid()) {
// Get filtered and validated data
$data = $form->getData();
// ... Do something with the validated data ...
// If all tabs were shown, redirect the user to Thank You page
if($tabNum==2) {
// Redirect to "Thank You" page
return $this->redirect()->toRoute('application/default',
array('controller'=>'index', 'action'=>'thankYou'));
}
}
}
// Pass form variable to view
return new ViewModel(array(
'form' => $form,
'tabNum' => $tabNum
));
}
}
In your view template, you use the following code:
<form action="">
<hidden name="tab_num" value="<?php echo $this->tabNum++; ?>" />
<!-- add other form fields here -->
</form>
Can we edit the possible options for a choice field after the field has been created?
Let's say, the possible options for the choice field(a drop down box for categories) comes from my database. My controller would look like this:
public function addAction(Request $request){
//get the form
$categories = $this->service->getDataFromDatabase();
$form = $this->formFactory->create(new CategoryType(), $categories);
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action, such as saving the task to the database, redirect
}
return $this->templating->renderResponse('TestAdminBundle:Categories:add.html.twig',
array('form' => $form->createView())
);
}
This works. $categories is populated as a dropdown box so the user can select a category. What I don't like about this code is that it has to hit the "getDataFromDatabase" service again when the user hits submit and the form validates the input. This feels unnecessary to me; ideally it should only need to hit the service when validation fails and the form has to be regenerated for the user. I'm hoping to make the controller look something like this:
public function addAction(Request $request){
//get the form
$form = $this->formFactory->create(new CategoryType());
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action, such as saving the task to the database, redirect
}
$categories = $this->service->getDataFromDatabase();
$form->setData($categories); //this tells the choice field to use $categories to populate the options
return $this->templating->renderResponse('TestAdminBundle:Categories:add.html.twig',
array('form' => $form->createView())
);
}
You need to use EventSubscriber, check the docs, here: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-underlying-data
I am sure I am going about this the wrong way, but I need to unset an array key from one of my choices in a sfWidgetFormChoice. The only way to get that variable to the Form is from the action. Here's what I have:
Action:
$id = $request->getParameter('id');
$deleteForm = new UserDeleteForm();
$choices = array();
$choices = $deleteForm->getWidgetSchema('user')->getAttribute('choices');
unset($choices[$id]); //I obviously don't want the user to be able to transfer to the user being deleted
$this->deleteForm = $deleteForm;
Form:
$users = Doctrine_Core::getTable('sfGuardUser')->getAllCorpUsers()->execute();
$names = array();
foreach($users as $userValue){
$names[$userValue->getId()] = $userValue->getProfile()->getFullName();
};
// unset($names[$id]); //this works, but I can't figure out how to get $id here.
$this->widgetSchema['user'] = new sfWidgetFormChoice(array(
'choices' => $names
));
$this->validatorSchema['user'] = new sfValidatorChoice(array(
'required' => true,
'choices' => $names
));
Understanding forms and actions:
Usually we will setup a form with fields, print it in a html page and fill the form with data. Pressing the submit form button will send all the data to a method defined in your form action html attribute.
The method will receive and get a $request , with a lot of parameters and also the form with the data. Those values will be processed in the action.
Lets look how it exactly works in symfony:
Define and Setup a symfony form, like the one you have shown above.
Print the form and in the action parameter point to the submit method
which will receive the request:
<form action="currentModuleName/update"
Symfony will automatically send the request to the action.class.php
of your module, and will look for and send the data to the function
executeUpdate
public function executeUpdate(sfWebRequest $request){ //...
$this->form = new TestForm($doctrine_record_found);
$this->processForm($request, $this->form); }
After some checks, symfony will process the form and set a result
template.
processForm(sfWebRequest $request, sfForm $form)
{ ... } $this->setTemplate('edit');
In the processForm of your module action.class.php, you should process all the received values (request) also with the form:
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
if ($form->isValid())
{
$formValues = $this->form->getValues();
$Id = $formValues['yourWidgetName'];
}
}
You may check the following link for an example like yours, about how to process a sfWidgetFormChoice.
And now answering to the real question, in order to select the deleted users, add the following code in your action:
//process the form, bind and validate it, then get the values.
$formValues = form->getValues();
$choicesId = $formValues['choices'];
Pass variable from action to the form:
Excuse me if I have not understand your question at all but in case you need to pass some parameters from your action to the form, send the initialization variables in an array to the form constructor:
Pass a variable to a Symfony Form
In your case, get the list of users, delete the user you dont want and send the non deleted users to the form constructor.
You will need to redeclare/overwrite your form again in the configure() function so that you could change the initialization of the form. Copy and paste the same code into the configure() function and comment the line: //parent::setup();
class TbTestForm extends BaseTbTestForm
{
public function configure()
{
//.. copy here the code from BaseTbTestForm
//parent::setup();
$vusers = $this->getOption('array_nondeleted_users');
//now set the widget values with the updated user array.
}
}
I have created a form using zend form, which is in the form directory in the applications directory. I have created an instance of this form in the controller:
public function getBookSlotForm(){
return new Application_Form_BookSlot();
}
public function bookSlotAction()
{
$form = $this->getBookSlotForm();
$this->view->form = $form;
}
And displayed it to the user in the view:
echo $this->form;
When the user fills in the form, how do I do I store that data in variables in the model?
Tim is correct as far as he goes, but you seem like you need a little more detail. you seem to have no issue with getting your form displayed on the page. Now to get the data from that form into your controller and then on to any model you want is pretty simple an straight forward.
I'm going to assume you are using the post method in your form for this example.
When you post your form in any php application it will send it's data in an array form to the $_POST variable. In ZF this variable is stored in the frontcontroller in the request object and is accessed usually with $this->getRequest()->getPost() and will return an associated array of values:
//for example $this->getRequest->getPost();
POST array(2) {
["query"] => string(4) "joel"
["search"] => string(23) "Search Music Collection"
}
//for example $this->getRequest()->getParams();
PARAMS array(5) {
["module"] => string(5) "music"
["controller"] => string(5) "index"
["action"] => string(7) "display"
["query"] => string(4) "joel"
["search"] => string(23) "Search Music Collection"
}
as a special case when using forms that extend Zend_Form you should access your form values using $form->getValues() as this will return form values that have had the form filters applied, getPost() and getParams() will not apply the form filters.
So now that we know what we are receiving from the process of sending the values to the model is pretty simple:
public function bookSlotAction()
{
$form = $this->getBookSlotForm();
//make sure the form has posted
if ($this->getRequest()->isPost()){
//make sure the $_POST data passes validation
if ($form->isValid($this->getRequest()->getPost()) {
//get filtered and validated form values
$data = $form->getValues();
//instantiate your model
$model = yourModel();
//use data to work with model as required
$model->sendData($data);
}
//if form is not vaild populate form for resubmission
$form->populate($this->getRequest()->getPost());
}
//if form has been posted the form will be displayed
$this->view->form = $form;
}
Typical workflow is:
public function bookSlotAction()
{
$form = $this->getBookSlotForm();
if ($form->isValid($this->getRequest()->getPost()) {
// do stuff and then redirect
}
$this->view->form = $form;
}
calling isValid() will also store the data in the form object, so if validation fails, your form will be redisplayed with the data the user entered filled in.