Passing POST value from VIEW to CONTROLLER to MODEL in Codeigniter - php

Ok I stripped out validation and other code to make this example as transparent as possible. I am unable to POST a VAR to my MODEL.
VIEW
<?php echo form_open('invoice'); ?>
<?php echo validation_errors(); ?>
<?php echo form_input('order_num', $this->input->post('order_num')); ?>
<?php echo form_submit('submit','submit'); ?>
<?php echo form_close(); ?>
CONTROLLER
public function invoice()
{
$order = $this->input->post('order_num');
$this->General_Model->get_customer_order($order);
}
MODEL
function get_customer_order($order)
{
. . .
$this->db->where('client_orders.id', $order);
$result = $this->db->get('client_orders');
. . .
}
Ok Basically you enter an order number on the form. Then it goes to the controller which does the validation (i removed it here to keep example simple) and finally it passes the data to the model which runs the query on the db and returns the $result.
However instead of my desired output im getting: Fatal error: Call to a member function get_customer_order() on a non-object and A PHP Error was encountered Severity: Notice Message: Undefined property: Account_dashboard::$General_Model
What am I doing wrong here? Thanks for the help.

Make sure you're loading the model in your controller:
$this->load->model('General_Model');
The controller line should
$data['order'] = $this->General_Model->get_customer_order($order);
Then you pass $data to the view.

Related

How to codeigniter Sending Parameters Between Controller and View different function

I'm new codeigniter developer.
I trying sending controller between views but only index function sending.
When I try different function, I get this error.
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: sample
Filename: views/merhaba_sayfasi.php
Line Number: 8
My controller file = merhaba.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Merhaba extends CI_Controller {
public function index()
{
$data["title"]="İlk codeigniter sayfam";
$data["giris_baslik"] = "Merhaba Dünya";
$this->load->view('merhaba_sayfasi',$data);
}
public function example(){
$data["sample"] = "Sample php";
$this->load->view("merhaba_sayfasi",$data);
}
}
?>
My view file = merhaba_sayfasi.php
<html>
<head>
<meta charset="utf-8">
<title><?php echo $title; ?></title>
</head>
<body>
<h3><?php echo $giris_baslik; ?></h3>
<?php echo $sample; ?>
</body>
</html>
My explorer image
http://www.medyasef.com/questions/codeigniter_function_error.png
It depends what URL you are calling?
If you call "/app/Merhaba" or "/app/Merhaba/index" you will not see the sample variable.
If you call "/app/Merhaba/example" then you should see it. It all depends what function of the controller you are calling - by default its only the index function
You're trying to display a variable, whose value hasn't been set, that's why the error is being thrown.
You could check in your view to ensure that a variable has a value before attempting to echo it.
So, instead of:
<?php echo $sample; ?>
You could use:
<?php if(isset($sample)) {echo $sample;} ?>
Although, I'd recommending keeping the logic in your controller and setting all of the values in your controller before loading the view

Laravel show errors in view

if my validation fails I do this:
return Redirect::back()->with('validation', $validation->errors->all());
also I am using:
$restful = true;
so when I am on get_edit() - I'am getting an error that there are no $validation variable when generating my view, when in post_edit() - its all okay because its returns a redirect with errors...
this is my view:
<? foreach($validation as $e): ?>
<div><?= $e; ?></div>
<? endforeach; ?>
undefined variable $validation, right now I'am trying to put it on the Router::before
Route::filter('before', function()
{
View::share('validation', array());
});
so the variable exists but is empty, but now arises a new problem, everytime after this filter executes it overrides those $validation that generates my post_edit(), also i've seen a variable $errors in my view but is ever empty, i don't how to use it, can you help me?
so shortly my problem is:
public function get_edit($id)
{
//generate my view with all nessesary data, but i can't generate here an error variable
// or its better to put it in one place to globally share it in the views, otherwise i am //getting an error
}
public function post_edit($id)
{
//validating $_POST data, if there is an error redirect it back to the get_edit() WITH a //variable containing errors
}
Did you read the docs? http://laravel.com/docs/5.0/validation#error-messages-and-views
You can use return Redirect::back()->withErrors($validation);
In your views, you can always use redirect('register')->withErrors($validator)$errors, without binding them to the view.

How to pass $$variables to view from controller in CakePHP?

in AppController:
function beforeFilter() {
$company = 'name of Company';
$this->set(compact('company'));
}
in Controller class:
function companyinfo() {
$logo = '<div><?php $this->Html->image('logo'); ?></div>';
$welcome = 'welcome to $$company!';
$this->set(compact('logo','welcome'));
}
function beforeFilter() {
parent::beforeFilter();
}
in View class:
<html>
<body>
<?php echo $logo; ?>
<?php echo $welcome; ?>
</body>
</html>
it doesn't answer variable in view after passing the variable from AppController via controller..
1) When you use $this->set(compact('company'));, it is NOT setting a variable for use in any controller - it's passing $company to the view.
2) You're trying to write PHP code in a string, using a Helper (which are only available in Views)
$logo = '<div><?php $this->Html->image('logo'); ?></div>';
3) It's unusual to want to pass data from AppController to Controller to View.
What you probably want to do is something like this:
//App Controller
function beforeFilter() {
$company = 'name of Company';
$this->set(compact('company'));
}
//Controller
function companyinfo() {
$logo = 'logo';
$this->set(compact('logo'));
}
//Layout file (or view file, but I assume it's layout since you're getting data in the AppController)
<?php
echo '<div>' . $this->Html->image($logo) . '</div>';
echo "Welcome to " . $company;
I mean this in the most constructive way possible (we've all been there). It seems like you're struggling with some general PHP concepts. Before you get too heavy into CakePHP, I recommend trying out a few lengthy tutorials in generic PHP - then when you feel completely comfortable with it, dive into CakePHP.
To get company into the view you can set it in your appcontroller if you want it avaiable in ALL views throughout your site or inside a specific controller if you only want it available in the view of the function you set it inside of. Either way you'll need to make correct use of the set function. For example:
$this->set('company', 'Name of Company');
OR
$company = 'Name of Company';
$this->set('company', $company);
Afterwards you'll be able to access the $company variable in the view.
echo $company; outputs Name of Company
As for your question for Dave:
<?php $welcome = 'Welcome to $$company'; ?> <html><body><?php echo $welcome; ?></body></html>
would be written as:
<html><body><?php echo "Welcome to ". $company; ?></body></html>
However, you should really look into using layouts with cakephp so you don't need to the <html>, <head>, <body>, etc. tags in every view file

CakePHP controller/action question with http://mysite.com/mycontroller/absentaction

Suppose someone hits in url http://mysite.com/comments/view/13
But that absentaction is not present in comments controller.
Then it gets normal error like that =>
Error: The action view is not defined in controller CommentsController
Error: Create CommentsController::view() in file: app/controllers/comments_controller.php.
<?php
class CommentsController extends AppController {
var $name = 'Comments';
function view() {
}
}
?>
Notice: If you want to customize this error message, create app/views/errors/missing_action.ctp
What i'm trying to do is that if someone hits url http://mysite.com/comments/view/13 and if the action is not present then it will redirect to http://mysite.com/.
How can i do this for unknown/absent action?
This trick is actually working pretty well.
You need to create a file app/app_error.php
<?php
class AppError extends ErrorHandler {
public function error404($params){
extract($params);
if(!isset($url)){
$url = $action;
}
if(!isset($message)){
$message ="";
}
if(!isset($base)){
$base = "";
}
$this->controller->redirect(array('controller'=>'pages','action'=>'home'));
//Or the page you want...
}
}
?>
How does it work?
It actually override the error404() function from the ErrorHandler and redirect the user whith $this->controller->redict();
Notice at the bottom of the error message, it says you can customize it by creating app/views/errors/missing_action.ctp. So all you need to do is create that .ctp file and include a redirect in it like this:
<?php
header( 'Location: http://mysite.com' ) ;
?>
It says it right in the error...
create app/views/errors/missing_action.ctp
And that's what you should do...
Try using a header in the missing_action.ctp to redirect to where you want the page to go.
You can either customise app/views/errors/missing_action.ctp or you can turn off debugging in app/config/core.php

CakePHP check if user is logged in inside a view

I have the following code:
<?php
if (!$this->Auth->user())
{
echo $this->element('header');
}
else
{
echo $this->element('header-bar');
}
?>
inside my view which should show a different header for logged in users but throws the following error:
Notice (8): Undefined property: View::$Auth [APP/views/layouts/page.ctp, line 17]
Fatal error: Call to a member function user() on a non-object in /Users/cameron/Sites/thehive/app/views/layouts/page.ctp on line 17
How do I fix this? Thanks
You don't need to do $this->set(compact('authUser'));
only use this in View:
if ($this->Session->read('Auth.User')){
// do something
}
As of CakePHP 2.x:
<?php if (AuthComponent::user('id')): ?>
Logged in as <?= AuthComponent::user('name') ?>
<?php endif; ?>
Note: Also check out meotimdihia's answer below. It's got a lot of upvotes.
The Auth component is for use in the Controller. You'll want to check for authorization in the controller, then set a variable for the view, e.g., $this->set('authUser', $this->Auth->user());. Then in your view you can do:
if (!$authUser)
{
echo $this->element('header');
}
If you want this to be done automatically for all controller methods, you can look into modifying cake/libs/controller/app_controller.php so that it includes the Auth component.
To summarize the answers on this page, evaluate one of the following based on which version of CakePHP you are using:
For version 1.x
$this->Session->read('Auth.User')
For version 2.x
AuthComponent::user('id')
For version 3.x
$this->request->session()->read('Auth.User.id')
For version 4.x, using the Authentication component
$this->loadHelper('Authentication.Identity');
...
$this->Identity->isLoggedIn()
This works in Cakephp 3+ (juts modify: "Auth.User.username" to suit your session data)
<?php
if (is_null($this->request->session()->read('Auth.User.username'))) {
echo "....logged out";
} else {
echo "You are Logged in As " . $this->request->session()->read('Auth.User.username');
}
?>
its been a while that I have used CakePHP but as far as I can remember CakePHP
doesn't support Auth in View. What you can do of course is set a variable in the
controller to use it in the view
<?
class AppController {
....
function beforeFilter(){
....
$this->set('auth',$this->Auth);
}
....
}
?>
and then use it in the view like this
$auth->....
or you can use the AuthHelper written by Ritesh Agrawal
http://bakery.cakephp.org/articles/ragrawal/2008/07/29/authhelper
BTW
I think if it comes to only test if somebody is logged in #webbiedave's answer
is better MVC style wise.
Nevertheless if you have to access userdata in view the just extract the userinfo
from Auth component and set it in the controller as I showed you and use it in the view
Regards
Try this
class AppController extends Controller{
$this->user = false;
public function beforeFilter(){
$this->user = $this->Auth->user();
}
public function beforeRender(){
$this->set('logged_user',$this->user);
}
}
Now You can check $logged_user in the view as
if($logged_user){
// users logged in $logged_user have all the details
}else{
// not logged in
}
in cakephp 3 you can check authentication session in the view like this
if($this->request->Session()->read('Auth.User')){
//do when login
}
else{
//do not login
}
If it helps anyone out in cakephp version 3.7.8 session has been depriciated to getSession so to update Lee Nielsen's comment
if (is_null($this->request->getSession()->read('Auth.User.username'))) {
echo "....logged out";
} else {
echo "You are Logged in As " . $this->request->getSession()->read('Auth.User.username');
}
For cakephp 4.2.6 Strawberry with Auth Component
<?php
// Note: Change email param to yours
if (is_null($this->request->getSession()->read('Auth')->email)) {
?>
<?= $this->Html->link(__('Login'), [ 'action' => 'login','controller' => 'Users']) ?>
<?php
} else { ?>
<?= $this->Html->link(__('Logout'), [ 'action' => 'logout','controller' => 'Users']) ?>
<?php }
?>
You need to set the user details from a controller, preferably the AppController which is inherited by all controllers across your site. Create/amend your app_controller.php to contain this beforeFilter(); method.
<?php
class AppController extends Controller {
function beforeFilter() {
$user = $this->Auth->user();
$this->set(compact('user'));
}
This will set a var called $user to the views which will be empty if the user is not logged in, or contain their data if they are.
//In the views (or layout)
$session->check('Auth.User.id');
//In controller
$this->Auth->User('id');
I found something worth mentioning, In CakePHP 3.x session handler is deprecated,
if we want to access session in view, we can do it via request handler. we have to use
<?php
// For CakePHP 3.x to access all user information
$this->request->session()->read('Auth.User');
// For CakePHP 3.x to check session
if($this->request->session()->read('Auth.User.id')) {
}
?>

Categories