If condition for 2 forms(2 submit buttons) in one controller in CI - codeigniter

I have a controller auth and there are 2 methods login and register.
And it is working nicely.
However, I need to have another function called login_and_register which will have an if condition that will determine which part will be executed. If the login part (basically code from login method) or register part (code from register method).
The if condition should be checking which submit button was clicked.
But here is the problem.
I need the form_open for both forms (login and register) stay like this:
<?php echo form_open('auth/login_and_register'); ?>
And this cannot be changed to e.g. auth/login_and_register_log or auth/login_and_register_reg or auth/login_and_register/log or auth/login_and_register/reg etc.
The login and register forms are in the same view and after submit is pressed this function login_and_register in auth controller is exectuted.
I was thinking that I can make the if condition base on the name of submit value, because for login form it is called submitlog and for registration form it is called submitreg.
So, maybe something like this:
if( isset($this->form_validation->set_value('submitlog')) ) {
//code for login part
}
elseif ( isset($this->form_validation->set_value('submitreg')) ) {
//code for registration part
}
else {
//code for redirect to homepage
}
But it is not working. Any idea why?

Querying the submit button names is a good idea. Here is a piece of code that works:
if ($this->input->post("submitlog") !== false) {
//code for login part
} elseif ($this->input->post("submitreg") !== false) {
//code for registration part
} else {
//code for redirect
}

instead of that, you can keep a hidden field in both the forms with the value of corresponding form name. In the controller you can check this field value and identify which form is submitted. Then you can redirect into the required function..

Related

client side validation not working for model window / ajax-loaded-form in yii

I am using Yii-user extension in the main layout i have a sign up link which is common to all the Cmenu
view/main layout
echo CHtml::link('Signup','#',array('id'=>'regi'));
$("#regi").click(function(){
$.ajax({
type:'GET',
url:'<?php echo Yii::app()->request->baseUrl;?>/index.php/user/registration',
success:function(res){
$("#dispdata").show();
$("#dispdata").html(res);
}
});
});
<div id="dispdata"><div>
**yii user extension **renders this perfectly and even submit its correctly if form values a re valid.
but if the values are incorrect and blank it redirect to url .../user/registration
which is not what my need .I need guidance what do i do such that if the values are incorrect or blank it should not redirect and display the errors in model window.
I did tried but hardly could get the satisfied results
if i place the following the model window itself doesnt appear what do i do
module registrationController i placed
....//some code here (**in yiiuser register controller**)
if ($model->save()) {
echo CJSON::encode(array(
'status'=>'success',
));
}
....//some code here...
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderPartial('registration',array('model'=>$model,),false,true);
in module view registration
<?php echo CHtml::ajaxSubmitButton(Yii::t('registration'),CHtml::normalizeUrl(array('user/registration','render'=>false)),array('dataType'=>'json',
'success'=>'function(data) {
if(data != null && data.status == "success") {
$("#registration-form").append(data.data);
}
}')); ?>
can anyone please guide me am working past 10 ten days tried every hook or crook method but could not obtain the results......how can the model window with client side validation be done appear..... Please guide me or let me know something better can be done
rules in registration model
if (!(isset($_POST['ajax']) && $_POST['ajax']==='registration-form')) {
array_push($rules,array('verifyCode', 'captcha', 'allowEmpty'=>!UserModule::doCaptcha('registration')));
as well was not with attributes for reqired field
have changed to
array_push($rules,array('verifyCode', 'captcha','message' => UserModule::t("captcha cannot be blank.")));
and added the verifycode to required field
yet not working,
The simple way is using render method in your Ajax action and creating empty layout for this action. If you do so, validation scripts will be included in the server response. Also you need to exclude jquery.js and other script with Yii::app()->clientScript->scriptMap and include them in main layout always.

How to repopulate form after form validation and also keep the URI?

I have a problem repopulating my form after validation fails. Problem is my url contains an additional uri which I access by clicking a link. This is what it looks like:
http://www.example.com/admin/trivia/add/5
At first trouble was that the segment 4 of the uri completely disappeared, so even though the validation errors showed and the form was repopulated, I lost my added uri.
Then I found in another question that the solution was to set form open like this:
echo form_open(current_url());
Problem is now it isn't showing any validation errors and the form is not repopulated. Is there a way to achieve this?
This is what my controller looks like:
function add()
{
$data = array('id' => $this->uri->segment(4));
if($_POST)
{
$this->_processForm();
}
$this->load->view('admin/trivia_form', $data);
}
And inside _processForm() I got all the validation rules, error message and redirecting in case success.
[edit] Here is my _processForm() :
function _processForm()
{
$this->load->library('form_validation');
//validation rules go here
//validation error messages
$this->form_validation->set_rules($rules);
$this->form_validation->set_error_delimiters('<div style="color:red">', '</div>');
if ($this->form_validation->run())
{
//get input from form and assign it to array
//save data in DB with model
if($this->madmin->save_trivia($fields))
{
//if save is correct, then redirect
}
else
{
//if not show errors, no redirecting.
}
}//end if validation
}
To keep the same url, you can do all things in a same controller function.
In your controller
function add($id)
{
if($this->input->server('REQUEST_METHOD') === 'POST')// form submitted
{
// do form action code
// redirect if success
}
// do your actual stuff to load. you may get validation error in view file as usual if validation failed
}
to repopulate the form fields you are going to need to reset the field values when submitting it as exampled here and to meke it open the same page you can use redirect() function as bellow:
redirect('trivia/add/5','refresh');
i don't know what you are trying to do, but try this to repopulate the form with the values user entered
<?php
echo form_input('myfield',set_value('myfield'),'placeholder="xyz"');
?>

Codeigniter Passing parameters from view to controller

view has this anchor:
echo anchor('login', 'Login or Register');
how do i send the current url to my controller login? and then use it on another function called login_validation?
all i want is, login and back to the last url, however nothing works. so i thought saving the current url when i click "Login or Register" and then after login, on function login_validation, i should redirect to that url saved...
controller index
public function index(){
$this->main_login();
}
main_login
public function main_login(){
$this->load->helper('url');
// on view i will call the next function login_validation
$this->load->view("view_login");
}
login_validation
public function login_validation(){
$this->load->library('form_validation');
(...)
if ($this->form_validation->run()){
// i should redirect the saved url here, instead of home
redirect('home');
}else{
(...)
}
}
i appreciate any help
You can do this simply by using $this->agent->referrer() in your controller class main_login().
Save the referrer url into your session, and once the user is validated (or if they are), then you pull that string from session:
in main_login():
// grabs url where you clicked login
$this->session->set_userdata('referrer_url', $this->agent->referrer());
in login_validation():
// pull url from session and redirect, make sure to account for not having url too
redirect( $referrer_url );
I apologize for the delay, i was really busy with the end of the semester,
So i will explain how i did to solve this problem, all i wanted was back to the current page after the login.. so, everytime i open my view login i will save the last page url, with this code:
$refering_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '' ;
and then i should save it in my session, so i can access from my controller and redirect the user to the last page, but look, i can’t simple save the url every time i access the view login, beucase every time i miss the password, i will be redirected to the login page, and so the last url, will the login and not the last one, and of course its wrong, So we have to save it on session, but only in the first time we access the view login, to do that, i compare the variable above ($refering_url) to the view login and view login validation, if its not the same, i can confirm that the previous page is the one i was before the login, and then i can save it to my session,
here the comparison, and the last url saved in my session:
if (($refering_url != ‘URL TO VIEW LOGIN‘) &&
($refering_url != ‘URL TO LOGIN VALIDATION){
$this->session->set_userdata('url', $refering_url);
}
after login is validated, on the controller, i should redirect the user , to the last page he was (the url saved on the session), to do that i used this code:
$this->session->set_userdata($data);
$url=$this->session->userdata('url');
redirect($url, 'refresh');

how to use last insert id when redirect same form page in codeigniter

I just try to prevent re submission problem when refresh form page. so I use session flashdata() method and redirect same form page. but I want also display recent inputed data on form VIEW page. then I am try $this->db->insert_id() on my form VIEW page . but it always show 0. how can I solve it?
when you redirect the user after the successful form submission then add the parameter in the url just a exapmle with dummy code to make an idea for you
$insertedid=$this->my_model->add_info();
//your add_info() should return the inserted id
redirect("/myformcontroller/myformpage/".$this->db->insert_id());// add id in redirect url
on your myformcontroller controller's myformpage function
function myformpage() {
$insertedid=$this->url->segment(3);
if(!empty($insertedid)){
//get new added information and pass it to view
}
// your other code
}
hope it makes sense

Codeigniter Form Validation: How to redirect to the previous page if found any validation error?

I am using Codeigniter's validation class to validate my form. Could you please tell me how to redirect to the previous page from controller if found any validation error?
In my controller:
if ($this->form_validation->run() == FALSE){
//**** Here is where I need to redirect
} else {
// code to send data to model...
}
I extended the URL helper for this.
https://github.com/jonathanazulay/CodeIgniter-extensions/blob/master/MY_url_helper.php
In your controller:
$this->load->helper('url');
redirect_back();
Just put the MY_url_helper.php in application/helpers and you're good to go.
UPDATE
You want to post a form, validate it, then show the form again with the validation errors if validation fails, or show something entirely different if validation passes.
The best way to do this is to post a form back to itself. So the action of your form would be action="". This way, in your method, you can check to see if the form was submitted, and determine what to do there:
// in my form method
if ($this->input->post('submit')) // make sure your submit button has a value of submit
{
// the form was submitted, so validate it
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
}
else
{
// the form wasn't submitted, so we need to see the form
$this->load->view('myform');
}
OLD ANSWER
You can always pass the current URI in a hidden field in the form:
<input name="redirect" type="hidden" value="<?= $this->uri->uri_string() ?>" />
And then redirect if the validation fails:
redirect($this->input->post('redirect'));
Or you can set the redirect url in a flashdata session variable:
// in the method that displays the form
$this->session->set_flashdata('redirect', $this->uri->uri_string());
And then redirect if the validation fails:
redirect($this->session->flashdata('redirect'));
Well, usually you should do like this (pseudocode for now):
if form_validation == false --> the form is either not submitted yet or validation failed --> load the form view;
if form_validation == true --> do the processing.
This means you have to stay within the same controller. Your code should already be doing this behaviour, which is the intended one.
If you still feel the urge to redirect, call the appropriate function:
redirect('updatebatch/get/40','refresh');
// assuming 'updatebatch' is the name of your controller, and 'sundial' just a folder
I have created a function inside a library to create redirects when I need them.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Functions {
public function generateRedirectURL()
{
$CI =& get_instance();
$preURL = parse_url($_SERVER['REQUEST_URI']);
$redirectUrl = array('redirectUrl' => 'http://' . $_SERVER['SERVER_NAME'] . $preURL['path']);
$CI->session->set_userdata($redirectUrl);
}
}
//End of the file
and when you want to create the redirect to that page, just write on the function:
$this->load->library('functions'); //you can put it in the autoloader config
$this->functions->generateRedirectURL();
Then you only need to call:
redirect($this->session->userdata['redirectUrl']);

Resources