Stay on current page after submit button in YII Framework - php

I am trying to submit a form , after form submition the current page should stay on with user entered datas . how to achieve this ?
public function actionUpload()
{
$model=new UploadModel();
$basemodel=new BaseContactList();
$importmodel=new ImportedFilesModel();
$importmodel->name =$basemodel->name;
$importmodel->import_date = $now->format('Y-m-d H:i:s');
$importmodel->server_path = $temp;
$importmodel->file_name = $name;
$importmodel->crm_base_contact_id = $crm_base_contact_id;
if ($importmodel->save())
echo "Import saved";
else
echo "Import Not Saved";
unset($_POST['BaseContactList']);
$this->redirect(Yii::app()->request->urlReferrer);
}
This line "$this->redirect(Yii::app()->request->urlReferrer);" goes to previous page but the user entered values are cleared . How to redirect to previous page without clearing the values in the form ??

Same with when you view the error message after failed model saving. Instead of doing redirection, you can just pass the saved model to the form.
public function actionIndex(){
$model = new Model();
if (isset($_POST[get_class($model)]){
$model->setAttributes($_POST[get_class($model)]);
if ($model->save()){
//do nothing
//usually people do a redirection here `$this->redirect('index');`
//or you can save a flash message
Yii::app()->user->setFlash('message', 'Successfully save form');
} else {
Yii::app()->user->setFlash('message', 'Failed to save form');
}
}
//this will pass the model posted by the form to the view,
//regardless whether the save is successful or not.
$this->render('index', array('model' => $model));
}
In the index view you can do something like.
<?php if (Yii::app()->user->hasFlash('message')):?>
<div class="message"><?php echo Yii::app()->user->getFlash('message');?></div>
<?php endif;?>
<?php echo CHtml::beginForm();?>
<!-- show the form with $model here --->
<?php echo CHtml::endForm();?>
The downside is, when you accidentally hit Refresh button (F5), it will try to post the form again.
Or you can save it using user session using setFlash.
public function actionUpload()
{
$model=new UploadModel();
$basemodel=new BaseContactList();
$importmodel=new ImportedFilesModel();
$importmodel->name =$basemodel->name;
$importmodel->import_date = $now->format('Y-m-d H:i:s');
$importmodel->server_path = $temp;
$importmodel->file_name = $name;
$importmodel->crm_base_contact_id = $crm_base_contact_id;
if ($importmodel->save())
echo "Import saved";
else
echo "Import Not Saved";
unset($_POST['BaseContactList']);
//here we go
Yii::app()->user->setFlash('form', serialize($basemodel));
//
$this->redirect(Yii::app()->request->urlReferrer);
}
In the previous form, you load the value from the session.
public function actionForm(){
if (Yii::app()->user->hasFlash('form')){
$basemodel = unserialize(Yii::app()->user->getFlash('form');
} else {
$basemodel = new BaseContactList();
}
$this->render('form', array('basemodel' => $basemodel));
}

I do not know whether really such a long code is needed to do such a thing but I can simply do it by this.
Suppose i have an actionUpdate
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Products']))
{
$model->attributes=$_POST['Products'];
$model->save();
// remove this redirect() line
// $this->redirect(array('view', 'id' => $model->productId));
}
$this->render('update',array(
'model'=>$model,
));
}
If in your action, you are redirecting after saving your data then just remove that line and you are done, provided that you are rendering the form again in the following lines
If you are not rendering the form in the next lines then you can do it yourself like
if($model->save())
{
$this->render('update',array(
'model'=>$model,
));
Yii::app()->end();
}

Will this do?
if ($importmodel->save())
$_SERVER['PHP_SELF'];

Simple Redirect to the same action and send the model loaded as an arguement

Related

Unable to load the requested file: validation.php

I am new to developing, and I want to do a simple validation in Codeigniter. I don't know where I am going wrong.
This is my form to be validated
And my controller is this
public function __construct()
{
parent::__construct();
$this->load->model('M_menu');
$this->load->model('master/M_user_type');
$this->load->helper(array('form'));
$this->load->library('form_validation');
}
public function index()
{
$data['menus']=$this->M_menu->getSideBarMenu_m();$data['error_message'] = '';
$this->load->view('master/V_user_type',$data);
}
function saveUserType_c()
{
$data['error_message'] = '';
$this->form_validation->set_rules('userType', 'UserTypeName', 'required');
echo var_dump($this->form_validation->run());
if (!$this->form_validation->run() )
{$data['menus']=$this->M_menu->getSideBarMenu_m();
$data['error_message'] .= validation_errors();
$this->load->view('master/V_user_type',$data);
}
else
{
$insert=$this->M_user_type->saveUserType_m();
if($insert){
$response=array("insert"=>true);
}else{
$response=array("insert"=>false);
}
echo json_encode($response);
}
}
With this I get the network error, and data is being saved to db. But no action in form(form not loading). Please guide me, where I go wrong. Also, if I need to give any more details
Please check your usertype view page, you can also load usertype view page before validation, so that you will be confirmed that usertype view page exist, I hope you understand my point.
You have to load a model before you call its methods. Use this:
$this->load->model('M_user_type');
$insert=$this->M_user_type->saveUserType_m();

codeigniter - how to prevent F5 from resubmitting a form

I have the following method in my controller:
(shortened version but all the key pieces are here...)
class Widget extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('widget_model');
$this->load->helper('form');
$this->load->library('form_validation');
}
public function assign()
{
//logic to display form.
if ($this->input->method() == "get" ) {
$data['save_status'] = '';
$data['title'] = 'Assign Widget';
$data['main_content'] = "assign";
$this->load->view('includes/template',$data);
}
else
{
//logic to handle POST
...
$data['save_status'] = 'Sucessfully saved to db';
$data['title'] = 'Assign Widget';
$data['main_content'] = "assign";
$this->load->view('includes/template',$data);
}
}
Everything works, except I don't know what the proper way to clear the form data is... because when I press F5 thinking I'm refreshing my page, it's actually resubmitting the data to the database.
Sorry, i'm sure this is a noob question.
Thanks.
EDIT 1
for now, I added a redirect at the end of post logic like this;
redirect(base_url()."index.php/thesamecontroller/thesamemethod");
and that takes the user to the same page, but without the form data being available.
Is this the best way to handle it?

Confirm form submission error in codeigniter grocery crud

When i click on back button, i got the confirm form submission error .How to prevent this issue?Please provide solution for this.
I am trying to login to the admi panel and edit in admin in this following code
Admin controller:
public function index()
{
$data = $this->data;
$this->load->view('admin/login.php',$data);
}
public function login()
{
$data = $this->data;
$username=$this->input->post("username");
$password=$this->input->post("password");
if($username=='admin'&&$password=='admin123')
{
$this->load->view('admin/home.php',$data);
}
else
{
$data['error']="Invalid Username or Password";
$this->load->view('admin/login.php',$data);
}
}
/* Function For Displaying the home page*/
public function home()
{
$data = $this->data;
$this->load->view('admin/index.php',$data);
}
/* Common Function for calling the View*/
public function _admin_output($output = null)
{
$output->base=$this->config->item('base_url');
$output->site=$this->config->item('site_url');
$output->css=$this->config->item('css');
$output->js=$this->config->item('js');
$this->load->view('admin/home_page.php',$output,'refresh');
}
public function loadSlidingimg()
{
$crud = new grocery_CRUD();
$crud->set_table('tbl_slideimg');
$crud->columns('imgname','active');
$crud->set_subject('Frontpage Sliding Images');
$crud->display_as('imgname','Image name');
$crud->set_field_upload('imgname','uploads');
$crud->display_as('active','Active Flag');
$crud->callback_after_update(array($this,'rename_slideimg_db'));
$crud->callback_after_insert(array($this,'rename_slideimg_db'));
$output = $crud->render();
$this->_admin_output($output);
}
}
Please provide solution for this issue
It happens because the action that took you to that page was a POST request. The browser wants to save you from unintentional double-ordering/paying/whatever when you go "back", when loading that page would need to do the form posted again.
How to work that around? I usually redirect the user to a page which was loaded by a GET request, it can be even the same page, see this answer: https://stackoverflow.com/a/3968038/357403
Or, you could modify the history: https://developer.mozilla.org/en-US/docs/Web/API/History_API
Also, please see the PRG pattern: https://en.wikipedia.org/wiki/Post/Redirect/Get
Try this code format:
$this->load->view('admin/home.php', 'refresh', $data);
or
redirect('home', 'refresh');

cakephp form action link

i am developing with cakephp (2.4.7) and i have a problem with a form action link.
I'm having a usersController with edit action.
public function edit($id = null, $slug = null) {
if (!$id) {
throw new NotFoundException(__('Invalid User'));
}
$user = $this->User->findById($id);
if (!$user) {
throw new NotFoundException(__('Invalid User'));
}
if ($this->request->is(array('post', 'put'))) {
// Do stuff here
}
// Fill the form
if (!$this->request->data) {
$this->request->data = $user;
}
}
with this code the form ($this->create->('User')); in the edit view get filled correctly. But i have another form in the edit view.
Like:
echo $this->Form->create(null, array(
'url' => array('controller' => 'useraddresses', 'action' => 'add')
));
echo $this->Form->input('searchvalue');
echo $this->Form->hidden('country');
echo $this->Form->hidden('city');
echo $this->Form->end('save');
When i click the send button from this form, the page links to /useraddresses/add/2 (2 is the id of the user)
I have debuged the form with firebug and in the action parameter is also /useraddresses/add/2.
How can i get arround this? I will to send the form to /useraddresses/add without any parameters.
If i delete this piece of code in my edit action, the action link is correctly but my first form does not get filled.
// Fill the form
if (!$this->request->data) {
$this->request->data = $user;
}
Use following
if(empty($this->data) )
{
if (!$this->request->data) {
$this->request->data = $user;
}
}
Instead of ur
if (!$this->request->data) {
$this->request->data = $user;
}

CodeIgniter - adding comments to a post

I'd like some help please. I have a post page that has the full post and below the post a small form for adding comments. The uri of the post page is: site/posts/1, so it is in posts controller, and the form action is form_open(site_url('comments/add/'.$post->post_id)).
This is my add() function inside comments controller:
public function add($post_id){
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$result = $this->comment_model->add($post_id);
if ($result !== false) {
redirect('posts/'.$post_id);
}
// TODO:load the view if required
}
and this is the add() function inside the comment model
public function add($post_id){
$post_data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment')
);
if ($this->validate($post_data)) {
$this->db->insert('comments', $post_data);
if ($this->db->affected_rows()) {
return $this->db->insert_id();
}
return false;
} else {
return false;
}
}
What I'm trying to do is if the $result = $this->comment_model->add($post_id); fails the validation to display the validation errors in my post view, else insert the comment and redirect to the same post page (site/posts/1).
The problem is that when I hit submit the form action goes in the comments/add/1, as expected, but doesn't do any these above.
Any ideas how can I fix this??
EDIT
I did a small change to the code without the 'confusing' validate() function. Maybe this is more helpful.
Comment controller:
public function add($post_id){
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$this->form_validation->set_rules($this->comment_model->rules);
if ($this->form_validation->run() == true) {
echo "Ok! TODO save the comment.";
// $this->comment_model->add($post_id);
// redirect('posts/'.$post_id);
} else {
echo "Validation Failed! TODO: show validation errors!";
}
// TODO:load the view if required
}
Comment model:
public function add($post_id){
$post_data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment')
);
$this->db->insert('comments', $post_data);
if ($this->db->affected_rows()) {
return $this->db->insert_id();
}
return false;
}
You need away of passing validation_errors() back to your Posts controller. At the minute, when you perform the redirect in your add function (when the validation fails), you loose the validation errors thrown.
I would consider using flashdata (http://ellislab.com/codeigniter/user-guide/libraries/sessions.html) to pass a success/error message from your Comments controller back to your Posts controller. Something similar to the below:
Comments Controller:
public function add($post_id) {
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$this->form_validation->set_rules($this->comment_model->rules);
if ($this->form_validation->run() == true) {
// Store the success message in flash data
$this->session->set_flashdata('message', 'Ok! TODO save the comment.');
// Redirect back to posts page
redirect('posts/'.$post_id, 'refresh');
} else {
// Store the error message in flash data
$this->session->set_flashdata('message', validation_errors());
// Redirect back to posts page
redirect('posts/'.$post_id, 'refresh');
}
}
Posts Controller:
public function index($post_id) {
$this->data['message'] = $this->session->flashdata('message');
$this->load->view('posts', $this->data);
}
Posts View:
echo $message;
Might not be perfect but hope it helps...

Categories