Codeigniter passing data from controller to view - php

As per here I've got the following controller:
class User extends CI_Controller {
public function Login()
{
//$data->RedirectUrl = $this->input->get_post('ReturnTo');
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('User_Login', $data);
}
//More...
}
and in my User_Login.php view file I do this:
<?php print_r($data);?>
which results in:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: views/User_Login.php
Line Number: 1
Do I need to load any specific modules/helpers to get the $data variable populated? If I print_r($this), I can see a lot of stuff but none of my data except in caches
Edit: To clarify, I know that calling the variable the same in the controller and view won't "share" it - it's out of scope but in the example I linked, it seems to imply a $data variable is created in the scope of the view. I simply happened to use the same name in the controller

Ah, the $data array's keys are converted into variables: try var_dump($title); for example.
EDIT: this is done using extract.

you should do it like :
echo $title ;
echo $heading;
echo $message;

Or you can use it like array.
In Controller:
...
$this->load->view('User_Login', array('data' => $data));
...
In View:
<?php print_r($data);?>
will show you the Array ( [title] => My Title [heading] => My Heading [message] => My Message )

you can pass a variable in the url to
function regresion($value) {
$data['value'] = $value;
$this -> load -> view('cms/template', $data);
}
In the view
<?php print_r($value);?>

You can't print the variable $data as it is an associative array....you may print every element of the associative array.....consider the following example.
Don't do as follows:
echo $data;
Do as follows:
echo $title;
echo $heading;
echo $message;

You can use this way also
$data['data]=array('title'=>'value');
$this->load->view('view.php',$data);

while sending data from controller to view we pass it in array and keys of that arrays are made into variables by code codeigniter and become accessible in view file.
In your code below all keys will become variables in User_Login.php
class User extends CI_Controller {
public function Login()
{
$data = array(
'title' => 'My Title', //In your view it will be $title
'heading' => 'My Heading', //$heading
'message' => 'My Message' //$message
);
$this->load->view('User_Login', $data);
}
}
and in your User_Login.php view you can access them like this:
echo $title;
echo $heading;
echo $message;

Related

Using blade data value into another one within layout

I want to use a variable value into another one (both are in the same table as keys) and display in a blade layout the container variable value. Both variables are passed using the with method from the controller. Is that possible?
Here a quick demo of what I'm loooking for :
# controller method
public function build()
{
return $this
->view('emails.registration_following')
->with( ['name' => 'Nick', 'text' => 'Hello {{ $name }}'] ) # Here goes the thing
;
}
And the blade.php looks like :
<html>
<body>
<p> {{ $text }} </p>
</body>
</html>
The expect output by me is Hello Nickbut I got Hello {{Nick}}. I know that brackets here, are treated like String but how to circumvine that?
How about defining the variable in the function first:
# controller method
public function build()
{
$name = 'Nick';
return $this
->view('emails.registration_following')
->with( ['name' => $name, 'text' => "Hello $name"] ) # Here goes the thing
;
}
In this way, you have both $name and $text accessible in the view.
In fact, I did not need to pass two variables but just one and put in its value all needed other variables to form my expected text.
It was a bad idea to do what I was asking for. Thank you.
Have u tried like this below?
public function build()
{
$name = 'Nick';
return $this
->view('emails.registration_following')
->with( ['name' => $name , 'text' => 'Hello '.$name] ) # Here goes the thing
;
}
with( ['name' => 'Nick', 'text' => "Hello $name"] ) Please use double quote

How to pass data controller to view in codeigniter

I am getting user profile fields from the database and want to display in my view but don't know to do this with the master layout.
this is my model
function fetchProfile($id,$page){
$query = $this->db->query("SELECT * FROM staff_master WHERE Id='$id'");
return $query->result();
}
this is my controller:
public function edit($id,$page){
$data['query'] = $this->StaffModel->fetchProfile($id,$page);
$data= array('content'=>'view_staff_edit');
$this->load->view('template_master',$data);
}
I am also trying to find a solution. I am passing user Id and another by URL (get method).
You are overwriting $data['query'] when you assign the array next:
$data['query'] = $this->StaffModel->fetchProfile($id,$page);
$data= array('content'=>'view_staff_edit');
Either do:
$data= array('content'=>'view_staff_edit');
$data['query'] = $this->StaffModel->fetchProfile($id,$page); // note position
Or:
$data = array(
'content' = 'view_staff_edit',
'query' => $this->StaffModel->fetchProfile($id,$page),
);
Access in view via $query and $content.
Unrelated:
You are also missing $page in your query, and its generally a good idea to declare gets as null if not set or you will get a notice: public function edit($id=null,$page=null){
Your overriding your first declaration of variable $data what you can do is to initialize them both at the same time.
Controller
public function edit($id,$page){
$data = array(
'query' => $this->StaffModel->fetchProfile($id,$page),
'content' => 'view_staff_edit'
);
$this->load->view('template_master',$data);
}
Then access it on your View file
<h1><?php echo $content ?></h1>
<?php foreach($query as $result): ?>
<p><?php echo $result->id ?></p>
<?php endforeach; ?>
Try doing something like this:
public function edit($id,$page) {
$data['query'] = $this->StaffModel->fetchProfile($id,$page);
$data['content']= 'view_staff_edit';
$this->load->view('template_master',$data);
}
YOUR MODEL
function fetchProfile($id){
return $this->db->get_where('Id' => $id)->result_array();
}
YOUR CONTROLLER
public function edit($id,$page){
$data = array(
'query' => $this->StaffModel->fetchProfile($id),
'content' => 'view_staff_edit',
);
$this->load->view('template_master',$data);
}
YOUR "template_master" VIEW
<?php foreach ($query as $res){?>
<span><?php echo $res['Id'];?></span> //User html content according to your requirements ALSO you can add all columns retrieved from database
<?php } ?>

Passing data from controller function to controller function before redirect

I am using codeigniter I have an edit page which shows me all information of a vacancy.
The (Vacancy) controller method to load this view looks like this, it makes sure all data is preloaded.
public function editVacancy($vacancyid)
{
$this->is_logged_in();
$this->load->model('vacancy/vacancies_model');
// Passing Variables
$data['title'] = 'Titletest';
$data['class'] = 'vacancy';
$orgadminuserid = $this->vacancies_model->getOrgAdminUserId($vacancyid);
if ((!is_null($orgadminuserid)) && ($this->auth_user_id == $orgadminuserid[0]->user_id)) {
$data['vacancyid'] = $vacancyid;
$data['vacancy'] = $this->vacancies_model->get($vacancyid);
$data['test'] = $this->session->flashdata('feedbackdata');
$partials = array('head' => '_master/header/head', 'navigation' => '_master/header/navigation_dashboard', 'content' => 'dashboard/vacancy/edit_vacancy', 'footer' => '_master/footer/footer');
$this->template->load('_master/master', $partials, $data);
}
}
In this view i have different forms for updating different sections.
Every form submit goes to a different method in my 'Vacancy' controller.
public function saveGeneralInfo()
{
$this->is_logged_in();
$this->load->model('vacancy/vacancies_model');
$vacancyid = $this->input->post('vacancyid');
$vacancyUpdateData = $this->vacancies_model->get($vacancyid);
$result = $this->vacancies_model->update($vacancyid, $vacancyUpdateData);
if ($result) {
$feedbackdata = array(
'type' => 'alert-success',
'icon' => 'fa-check-circle',
'title' => 'Success!',
'text' => 'De algemene vacature gegevens zijn geupdate.'
);
$this->session->set_flashdata('feedbackdata', $feedbackdata);
redirect("dashboard/vacancy/editVacancy/" . $vacancyid);
}
}
}
Where I indicated in my code "//HERE ..." is where I would want the feedback message parameter to pass on to my 'main controller method' which loads the view with the prefilled data. (editVacancy).
Is there a clean way to do this?
EDIT:
I tried using flashdata, i updated the code to have the flashdata inserted.
However when i do a var_dump($test); in my view, it remains null.
EDIT 2:
I noticed when i put my $_SESSION in a variable in my editVacancy controller method (which is being redirected to) and var_dump it in my view that this does not contain the ci_vars with the flashdata in.
Instead of using set_header you can use simple redirect function for it.
redirect("dashboard/vacancy/editVacancy/".$vacancyid);

Overwrite view()->share key in controller method?

Let say we have something like this in a AppServiceProvider
$page = [
'title' => 'Page Name',
'info' => 'Content Here'
];
view()->share('page', $page);
In view:
<h1>{{$page['title']}}</h1>
<p>{{$page['info']}}</p>
If I want to overwrite $page['title'] in method controller, I have tried like this:
public function index()
{
$page['title'] = "overwrite title only";
return view('index', compact('page'));
}
Problem is $page['info'] will not longer be available, it will not exist in view. How can I overcome this situation?
The simplest solution could be to replace in your Controller:
$page['title'] = "overwrite title only";
with:
$page = array_merge(
view()->shared('page'),
['title' => "overwrite title only"]
);
view()->shared() method returns the shared variable, then we can override some array elements and pass the overridden array to the view.

Template plugin in Codeigniter

i've been using and studying Collin Williams template plugin (http://williamsconcepts.com/ci/codeigniter/libraries/template/reference.html#manipulation) and i've already posted this issue on CI's forum but i think the last post was last year maybe its not being monitored by Colllin or wat but i guess i'll just have to post this here maybe you guys can help.
Original Post on CI Forum
Hello Collin,
I’ve been studying your template plugin lately, as i was following your guide,
i came across this line of code
$data = array('name' => 'John Smith', 'birthdate' => '11/15/1950');
$this->template->write_view('content', 'user/profile', $data, TRUE);
it was a bit confusing whether in the view files, like
mymastertemplate.php for example, how do i accessthe $data array, does
it have to be $content defined by that first param. a region, or by
$name and $birthdate? ... cuz’ it says there $content will display the
data array? its a bit confusing. Hope you could enlighten me.
Basically thats my problem.
On Template.php library we can see function write_view(). Now, focus on $data = NULL. Now then finds a file of existed data on APPPATH.'views/'.$suggestion.'.php' so I think that $args[0] should be a file which is loaded and break it, than loaded a view template on $data.
function write_view($region, $view, $data = NULL, $overwrite = FALSE)
{
$args = func_get_args();
// Get rid of non-views
unset($args[0], $args[2], $args[3]);
// Do we have more view suggestions?
if (count($args) > 1)
{
foreach ($args as $suggestion)
{
if (file_exists(APPPATH .'views/'. $suggestion . EXT) or file_exists(APPPATH .'views/'. $suggestion))
{
// Just change the $view arg so the rest of our method works as normal
$view = $suggestion;
break;
}
}
}
$content = $this->CI->load->view($view, $data, TRUE);
$this->write($region, $content, $overwrite);
}
In another way, $data should be as array which will response for View template data on Codeigniter library (standard view of CI: $this->CI->load->view(...))
$data = array('name' => 'John Smith', 'birthdate' => '11/15/1950');
$this->template->write_view('content', 'user/profile', $data, TRUE);
On template file '/user/profile.php' use as example:
HTML/PHP template file profile.php:
Your name: <?php echo $data["name"]; ?>
Your name: <?php echo $data["birthdate"]; ?>
And as I see, a CONTENT var must be an ARRAY due to documentation...
$template['default']['regions'] = array(
'header' => array(
'content' => array('<h1>Welcome</h1>','<p>Hello World</p>'), ### <----- AS EXAMPLE
'name' => 'Page Header',
'wrapper' => '<div>',
'attributes' => array('id' => 'header', 'class' => 'clearfix')
)
);
Regions must be defined as template, so if you didn't have header region that didn't work:
$template['default']['regions'] = array(
'header',
'content',
'footer',
);
!!!!!
Simply, he can't acces private access variable _ci_cached_vars which is stored data like $name. RELATED TOPIC: CodeIgniter shared data between calls to load->view

Categories