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
Related
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.
Everything looks right to me. It's so simple, but I dont know. I've looked everywhere.
Problem: It doesn't redirect. It doesn't give error nothing happens.
But when I enter the browser http://site.dev/fail
it shows "fail" word on screen (so it works).
routes.php:
Route::post('getir' , 'Ahir\Ticket\Controllers\TicketController#postInsert');
Route::get('fail', function() { return 'fail'; });
Route::get('success', function() { return 'success'; });
edit everything
Scenario:
on site.dev/ (homepage) I press submit that form has this.
form action="getir" method="POST" role="form"
so button redirect me to
Route::post('getir' , 'Ahir\Ticket\Controllers\TicketController#postInsert');
so this postInsert is triggered below at controller ticket.
controller ticket:
<?php namespace Ahir\Ticket\Controllers;
use BaseController, Input;
//use Ahir\Ticket\Repositories\TicketInterface;
use Ahir\Ticket\Adapters\AdapterInterface ;
class TicketController extends BaseController {
public function __construct(AdapterInterface $adapter) //TicketInterface $repository
{
//$this->repository = $repository;
$this->adapter = $adapter;
}
public function postInsert()
{
$this->adapter->postInsert();
}
}
then it comes here
codes
public function postInsert()
{
// create the validation rules ------------------------
$rules = array(
'title' => 'required',
'content' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// i added here return vardump('fail'); it displays on screen.
// so i know that program comes here
// but the redirect below neither gives error nor redirect.
//nothing happens here. idk why!
return Redirect::to('fail')->withErrors($validator);
} else {
// validation successful ---------------------------
$this->obj->insert([
'title' => Input::get('title') ,
'content' => Input::get('content')
]);
//here DOESNT work too.
return Redirect::to('success');
}
The problem is that you don't return anything from the calling function.
Your application calls the postInsert() method on your ticket controller. This function calls another function which returns a Redirect.
But you don't pass that returned Redirect back to the application, so the postInsert() function just terminates without any output. The application doesn't know what happens within the postInsert() function, it just waits for something to be returned. And since nothing is returned, the HTTP response is simply empty. In order to pass that Redirect back to the application, you also have to return it from the calling function:
public function postInsert()
{
return $this->adapter->postInsert();
}
I have setup the laravel resource controller and utilized the edit and update methods to edit user profiles. My profile form turned out to be too long, so I would like to split it into two forms.
The trouble is that the update function appears to be built into the resource controller - I tried just copy the method, add in my inputs and rename it. I updated the routes and view, but received an error. I also tried to have both forms call the same function, but the information that wasn't included in the form was delete from my db.
My question is, how do I split my form into two, so I can update my user profile from two forms instead of one? Any help would be appreciated. Thank you
For reference, here is my ContractorController
public function edit($id)
{
//
// get the contractor
$contractor = Contractor::find($id);
// show the edit form and pass the contractor
return View::make('contractors.edit')
->with('contractor', $contractor);
}
public function update($id)
{
//
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('contractors/' . $id . '/edit')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$contractor = Contractor::find($id);
$contractor->name = Input::get('name');
$contractor->tag_line = Input::get('tag_line');
$contractor->contact_name = Input::get('contact_name');
//would like to split items below into a separate form:
$contractor->public_email = Input::get('public_email');
$contractor->phone = Input::get('phone');
$contractor->address_1 = Input::get('address_1');
$contractor->city = Input::get('city');
$contractor->state = Input::get('state');
$contractor->zip = Input::get('zip');
$contractor->website = Input::get('website');
$contractor->story = Input::get('story');
$contractor->save();
// redirect
Session::flash('message', 'Successfully updated profile!');
return Redirect::to('contractors');
}
}
Start of form in edit.blade.php
{{ Form::model($contractor, array('route' => array('contractors.update', $contractor->id), 'class' => 'form-horizontal', 'method' => 'PUT')) }}
I found CodeIgniter form validation to show error message with load->view method, and will lost field error message if use "redirect".
Currently I use one function to show form page, and another function to deal form post.
class Users extends CI_Controller {
function __construct() {
parent::__construct();
}
public function sign_up()
{
$this->load->view('users/sign_up');
}
public function do_sign_up(){
$this->form_validation->set_rules('user_login', 'User Name', 'trim|required|is_unique[users.login]');
$this->form_validation->set_rules('user_email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('users/sign_up');
}else {
// save post user data to users table
redirect_to("users/sign_in");
}
When form validation failed, url in browser will changed to "/users/do_sign_up", I want to keep same url in sign_up page.
Use redirect("users/sign_up") method in form validation failed will keep same url, but validation error message will lost.
in Rails, I cant use routes to config like this:
get "users/sign_up" => "users#signup"
post "users/sign_up" => "users#do_signup"
imho it's not necessary to check the request method because if the user 'GET' to the page you want to show the sign up view... if they user 'POST' to the page and fails validation you ALSO want to show the sign up view. You only won't want to show the sign up view when the user 'POST' to the page and passes validation.
imho here's the most elegant way to do it in CodeIgniter:
public function sign_up()
{
// Setup form validation
$this->form_validation->set_rules(array(
//...do stuff...
));
// Run form validation
if ($this->form_validation->run())
{
//...do stuff...
redirect('');
}
// Load view
$this->load->view('sign_up');
}
Btw this is what im doing inside my config/routes.php to make my CI become RoR-like. Remember that your routes.php is just a normal php file so u can put a switch to generate different routes depending on the request method.
switch ($_SERVER['REQUEST_METHOD'])
{
case 'GET':
$route['users/sign_up'] = "users/signup";
break;
case 'POST':
$route['users/sign_up'] = "users/do_signup";
break;
}
Here is my approach in CodeIgniter 4. I think you only need one method to complete the task.
In your app/Config/Routes.php
/*
* --------------------------------------------------------------------
* Route For Sign up page
* --------------------------------------------------------------------
*/
$routes->match(['get','post'], 'signup', 'Users::Signup');
In your app/Views/signup.php
<?php print form_open('/signup', ['method' => 'POST']);?>
<!--All other inputs go here, for example-->
<input type="text" name="firstname">
<?php print form_close();?>
In your app/Controllers/Users.php
namespace App\Controllers
use App\Controllers\BaseController;
class Users extends BaseController
{
public function Signup(){
helper(['form', 'url']);
//run validations here
if ($this->request->getMethod() === 'post' && $this->validate([
'firstname' => [
'label' => 'Firstname',
'rules' => 'required|alpha_space',
'errors' => [
'required' =>'Please enter your <strong>Firstname</strong> e.g.John',
'alpha_space' => 'Only alphabetic characters or spaces for <strong>Firstname</strong> field'
]
],
])){
//do other stuff here such as save data to database
$first_name=$this->request->getPost('firstname');
//if all go well here you can redirect to a favorite page
//e.g /success page
return redirect()->to('/success');
}
//if is get or post
print view('signup');
}
}
<button type="submit"class="md-btn btn-sm md-fab m-b-sm indigo" id="filterbtn" formaction="<?php echo base_url(); ?>front/get_filter/<?php echo$device_id;?>"><i class="fa fa-bar-chart"></i></button>
<button type="submit"class="md-btn btn-sm md-fab m-b-sm indigo" id="filterbtn" formaction="<?php echo base_url(); ?>front/get_data/<?php echo$device_id;?>"><i class="fa fa-th-list"></i></button>
I have a form with some text fields and I have a preview button that needs to submit the form to the same controller. And then in the controller, I need to extract the values and populate a form with these values for the template to see. What is the best way to achieve this? I'm a newbe so please be clear.
Sample controller:
public function myControllerName(sfWebRequest $request)
{
$this->form = new myFormClass();
}
Use <?php echo $form->renderFormTag( url_for('#yourRoutingName'), array('method' => 'POST') ); ?> in your template and change #yourRoutingName to the one pointing to your controller.
Now change your controller to be something like this:
public function myControllerName(sfWebRequest $request)
{
$this->form = new myFormClass();
if ($request->isMethod(sfRequest::POST)
{
$this->form->bind( $request->getParameter( $this->form->getName() ) );
// Check if the form is valid.
if ($this->form->isValid())
{
$this->form->save();
// More logic here.
}
}
}
The $this->form->bind( $request->getParameter( $this->form->getName() ) ); part binds posted data to your form where $this->form->isValid() returns a boolean whether the form is valid or not.
Have you tried this ?
$this->redirect($request->getReferer()); //action
if not, then please try and check if its work for you.
Thanks.