Passing parameter between two function/view - codeigniter

I have two functions in controller named step1 and step2. I want to pass $data array between theme. Below is controller code. In step1 i have input in step2 i have simple echo which shows value of $data['text1']. This value is allays NULL in step2 controller, no meter what I type in step1.
public $data = array(
'id' => '',
'text1' => '',
'text2' => ''
);
public function __construct()
{
parent::__construct();
}
public function step1()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('text1', 'Text 1', 'rquired');
if($this->form_validation->run() === FALSE)
{
$this->load->view('test/step1', $this->data);
}
else
{
$this->data['text1'] = $this->input->post('text1');
redirect('test/step2');
}
}
public function step2()
{
$this->load->view('test/step2', $this->data);
}
public function step3()
{
}
}

You're redirecting to step2 by redirect('test/step2'); That basically reloads the page and your $data property gets emptied.
Instead, you should try something like that:
$this->data['text1'] = $this->input->post('text1');
$this->step2(); //would call your existing step2() method
If you actually want to have a header redirect to url like test/step2 , you may need to have your $data stored in a session.

Related

Laravel - return variable from Form Requests to Controller

How can I return a variable from Form Requests (App\Http\Requests) to Controller (App\Http\Controllers)?
I am saving a record on function persist() on Form Requests.
My goal is to pass the generated id so that I can redirect the page on edit mode for the user. For some reason, the Controller cannot receive the id from Form Requests.
App\Http\Requests\MyFormRequests.php:
function persist()
{
$business = Business::create([
'cart_name' => $this['cart_name'],
'product' => $this['product']
]);
return $myid = $business->id;
}
App\Http\Controllers\MyControllers.php:
public function store(MyFormRequests $request)
{
$request->persist();
return redirect()->route('mypage.edit.get', $request->persist()->$myid);
}
Important
I must add that this is not the recommended way. Your FormRequest should only be responsible for validating the request, while your Controller does the storing part. However, this will work:
App\Http\Requests\MyFormRequests.php:
function persist()
{
return Business::create([
'business_name' => $this['business_name'],
'nationality' => $this['nationality']
])->id;
}
App\Http\Controllers\MyControllers.php:
public function store(MyFormRequests $request)
{
$id = $request->persist();
return redirect()->route('register.edit.get', $id);
}
A guy name Snapey helped me:
public function store(MyFormRequests $request)
{
$business = $this->persist($request);
return redirect()->route('register.edit.get', $business->id);
}
private function persist($request)
{
....
return $business;
}
hope this could help someone in the future.

I am making admin panel in laravel 5.2, how to call function inside another function?

I want to know what is wrong in my code given below, I am make my code clean and problem arises since function is not called in another function.example my retrieve function is not called in form method...similary my saveintodatabase function in not called in form method?
there is my code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Register;
class Admincontroller extends Controller
{
public function form(Request $request)
{
return $this->retrieve($request);
$register= new Register;
return $this->saveintodatabase($name,$phone,$email,$course,$address);
if($register->save())
{
return redirect()->route('displaydata');
}
else
{
echo "fail to insert";
}
}
public function display()
{
$records = Register::all();
return view('displaydata',['records' => $records]);
}
public function delete($id)
{
$records = Register::destroy($id);
$records = Register::all();
if(count($records) > 0)
{
return redirect()->route('displaydata');
}
else
{
echo "No record found";
}
}
public function update($id)
{
$records = Register::find($id);
return view('updatedata',['records' => $records]);
}
public function afterupdate(Request $request)
{
return $this->retrieve($request);
$id=$request->id;
$register = Register::find($id);
if($register->save())
{
//$this->display();
return redirect()->route('displaydata');
}
else
{
echo "fail to insert";
}
}
public function __construct(Request $request)
{
$this->validate($request,[
'name' =>'required',
'phone' => 'required',
'email' => 'required',
'course' => 'required',
'address' => 'required',
]);
}
private function saveintodatabase($name,$phone,$email,$course,$address)
{
$register->name=$name;
$register->phone=$phone;
$register->email=$email;
$register->course=$course;
$register->address=$address;
}
private function retrieve(Request $request )
{
$name=$request->name;
$phone=$request->phone;
$email=$request->email;
$course=$request->course;
$address=$request->address;
}
}
From your code if form function is called then retrieve function should be called However:
your retrieve function does not return anything or change any value for form function. How can you know if it is called. Set XDebugger could be good for you to check. Or simple put die in retrieve function to see if you are there or not.
Chances are your validatoin is failed in your constructor for this you also need to check by either debugger or die method
Laravel 5 has middleware, check if you are using it to cause you never reach to form function

Codeigniter submit form not working, blank page

I'm attempting to submit a form with codeigniter and when i submit the form a get a blank page. Where did i go wrong?
View
echo "<form class='order_ctn_parent' method='POST' action='add/insert_orders'>";
//inputs
echo "</form>";
Controller
class Add extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index() {
}
public function insert_orders()
{
$this->load->model('order_model', 'order');
$this->order->insert_orders();
redirect('view_orders', 'location');
}
}
Model
class Order_model extends CI_Model {
public function insert_orders()
{
$DB2 = $this->load->database('orders', TRUE);
$timber_array = $this->input->post("timber_choose");
$products_array = $this->input->post("product_choose");
$qty_array = $this->input->post("quantity");
$price_array = $this->input->post("price");
$qty_array = $this->input->post("quantity");
$loop = 0;
foreach($products_array as $product) {
$price = str_replace("£","",$price_array[$loop]);
$data = array(
'product_code' => "",
'timber_type' => $timber_array[$loop],
'product' => $product,
'quantity' => $qty_array[$loop],
'price' => $price
);
$DB2->insert('timber_order_products', $data);
$loop++;
}
}
}
Try something like this
?>//end of php
<form class='order_ctn_parent' method='POST' action='<?php echo base_url()?>add/insert_orders'>
</form>
and load model in __construct(), like this
public function __construct()
{
parent::__construct();
$this->load->model('order_model', 'order');
}
and no need of check $DB2 = $this->load->database('orders', TRUE);
and Codeigniter insert should be Like This
Please check your url after submitting . i am sure your form action is not working . give proper controller and its function url into Form action . example is here .
<?php echo site_url('add/insert_orders);?>
where add will be your controller and insert_orders will be function of add controller.

How to load hook for particular controller

I am new in codeigniter. I want to load hooks for admin panel controller.
$hook['post_controller_constructor'][] = array(
'class' => 'AdminData',
'function' => 'myfunction',
'filename' => 'loginhelp.php',
'filepath' => 'hooks',
'params' => array()
);
Ok this is the simplest way to do this:
declare a public variable in your Controller
public $is_hookable = TRUE;
Then inside your hook function do this:
$ci=&get_instance();
if($ci->is_hookable){
... enter whatever you want here;
}
hope this was helpful
please read the document clearly https://ellislab.com/codeigniter/user-guide/general/hooks.html
The hooks feature can be globally enabled/disabled by setting the
following item in the application/config/config.php file:
$config['enable_hooks'] = TRUE;
Hooks are defined in application/config/hooks.php file.
You cannot load it for specific controller.You need to check controller name at hooks function and write code. suppose your post_controller_constructor hooks function name is myfunction you can check it inside the function
$CI =& get_instance();
if($CI ->router->class=="AdminData"){//write your code}
Application/config/hooks.php
$hook['post_controller'] = array(
'class' => 'LogoutBlockedUser',
'function' => 'logout',
'filename' => 'LogoutBlockedUser.php',
'filepath' => 'hooks',
'params' => ""
);
Enable hooks in config.php
$config['enable_hooks'] = TRUE;
Application/hooks/LogoutBlockedUser.php
class LogoutBlockedUser {
public function __construct()
{
}
public function logout()
{
$CI =& get_instance();
if(!(empty($CI->session->userdata('user_id'))))
{
$CI->load->model('Your_model', 'web');
$result = $CI->common->select_query;
if(!empty($result))
{
$CI->session->unset_userdata('user_id');
session_destroy();
redirect(base_url() . 'yourcontroller/function');
}
}
}
}
The post_controller_constructor hook gets called after a $class is loaded. The class that gets loaded is based on the route parameters.
system/core/Codeigniter.php
/**
*<code>
* http://example.com/adminData/method
*</code>
*
* $CI = new adminData(); => application/controllers/adminData.php
**/
$CI = new $class();
$EXT->call_hook('post_controller_constructor');
So if you wanted to call a method on the adminData controller, you could do something like this.
This method is not ideal, as its not very OOP like, however the way CI is built from a design point of view, you have to do a few workarounds like the example below
application/controllers/adminData.php
class AdminData extends CI_Controller
{
public function __construct(){}
// This cannot be called directly in the browser
public function _filter()
{
/**
* Put your logic in here
*<code>
* $this->model->logic()
*</code>
**/
exit('I have just be called!');
}
}
application/hooks/loginhelp.php
class AdminData
{
protected $ci;
public function __construct()
{
global $CI;
$this->ci = $CI;
}
public function myfunction()
{
// If the class is not == AdminData, just bail
if(get_class($this->ci) != 'AdminData') return;
if(!is_callable(array($this->ci, '_filter'))) return;
//calls $AdminData->_filter()
return call_user_func(array($this->ci, '_filter'));
}
}

Code Igniter - Unable to load requested file after redirect

I am VERY new to codeigniter so please excuse me if this is a n00bish sort of question...
I have a controller called dashboard.php:
class Dashboard extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('site_header');
$this->load->view('dashboard');
$this->load->view('site_footer');
}
else
{
//If no session, redirect to login page
echo 'hello there';
//redirect('main', 'refresh');
}
}
function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('home', 'refresh');
}
}
?>
This page loads fine when i access it via localhost/sitename/dashboard.
HOWEVER i am having issues trying to redirect to this controller from another controller of mine. The controller that is calling the redirect is verifyLogin.php (in same directory level)
class VerifyLogin extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
}
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected welcome page
redirect('');
}
else
{
//Go to private area
redirect('dashboard', 'index');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->ID,
'username' => $row->username,
'stay_logged' => true
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
}
?>
When the redirect() is called i get an error - Unable to load the requested file: dashboard.php
After this error, i can no longer access localhost/sitename/dashboard (i just get that same error).
Some advice would be amazing right now as well as a way of debugging this for future problems.
Cheers!
Use this pattern to redirect
redirect("controllername","function name");
or
redirect(base_url().'index.php/controller/function');
Trying to load a view that doesn't exist. Load dashboard.php to your view folder. I hope it works ;))
By looking at you problem, I think this should help you out use this:
redirect(site_url().'dashboard', 'index');
try this one in verifylogin controller
redirect('Dashboard', 'refresh');
Let me know the result

Resources