Converting array key and values into single variables - php

I know that you can use extract() to achieve this however my circumstances are as followed:
I am building a very small basic MVC framework for personal projects and I have this in my controller:
public function index(){
$data = [
'title' => 'Welcome'
];
$this->view('pages/index', $data);
}
As you can see this passes the data array into the view and you can echo it like:
echo $data['title'];
But I want to echo it like echo $title; I know that extract() can do this but that means I have to manually put extract($data); at the top of every page which isnt the end of the world but I was just curious if there was a way it could be done automatically? I have tried to use extract by putting it inside the view function but that did not work. I have also tried to use extract by putting it in the header file that is required_once in index.php (thus making the header file a static header thats always required) but neither has worked so any advice would be great.
Here is the code for the view function as requested:
public function view($view, $data = []){
if(file_exists('../../views/'.$view.'.php')){
require_once '../../views/'.$view.'.php';
} else {
die('View does not exist');
}
}

Simple that is it ,use compact and extract function
index method
public function index(){
$title='Welcome';
$this->view('pages/index', compact('title'));
}
Wiew method
public function view($view, $data = []){
extract($data);
if(file_exists('../../views/'.$view.'.php')){
require_once '../../views/'.$view.'.php';
} else {
die('View does not exist');
}
}
In html
<h1> hello <?php echo $title; ?></h1>

Here is where I went wrong, I put extract in the view method before and it didn't work.
However the advice here was to put it in the view function and I now understand that I put the extract function after require_once '../../views/'.$view.'.php'; I just put extract before that line of code and it is now working!

Related

Codeigniter passing data controller to view

Here is my controller:
class CommonController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('common_model'); //load your model my model is "common model"
}
public function add_work(){
$names = $_POST['name'];
$works = $_POST['work'];
$allValues = array(); // array to contains inserted rows
foreach($names as $key => $name){
$name= "your specified name";
$insertdata = array();
$insertdata['work'] = $works[$key];
$insertdata['name'] = $name;
$this->common_model->insert($insertdata);
array_push($allValues,$insertdata);
//$insert = mysql_query("INSERT INTO work(name,work) values ( '$name','$work')");
}
foreach($allValues as $insertRow){
echo $insertRow['work'];
echo $insertRow['name'];//this shows data well. but how to pass data in view.php
}
//view code will add here to show data in browser
}
Basically I want to pass all data to view.php for printing or exporting purpose. How can I do so.
To load a view you should do like this.
$this->load->view("filename");
If you want to pass data to view, you should do like this.
$this->load->view("filename",$data);
$data should have all parameters which you want to print in view.
The syntax goes like this.
$this->load->view("filename","data to view","Returning views as data(true / false");
If third parameter is true, view will come as data. It will not go to browser as output.
Edit:
Change
$this->load->view('print_view',$insertdata);
to
$data['insertdata'] = $insertdata;
$this->load->view('print_view',$data);
For more info, check this link
How CI Classes Pass Information and Control to Each Other
Calling Views
We will see.how the controller calls a view and passes data to it:
First it creates an array of data ($data) to pass to the view; then it loads and calls the view in the same expression:
$this->load->view('testview', $data);
You can call libraries, models, plug-ins, or helpers from within any controller, and models and libraries can also call each other as well as plug-ins and helpers.
However, you can't call one controller from another, or call a controller from a
model or library. There are only two ways that a model or a library can refer back to a controller:
Firstly, it can return data. If the controller assigns a value like this:
$foo = $this->mymodel->myfunction();
and the function is set to return a value, then that value will be passed to the variable $foo inside the controller.
//sample
public function display()
{
$data['text_to_display'] = $this->text_to_display;
$data['text_color'] = $this->text_color;
$this->load->view('display_view',$data);
}
Adding Dynamic Data to the View
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view
loading method. Here is an example using an array:
$data = array(
’title’ => ’some’,
’heading’ => ’another some’,
’message’ => ’and another some’
);
$this->load->view(’view’, $data);
And here’s an example using an object:
$data = new Someclass();
$this->load->view(’view’, $data);
Sending Multiple Dimensional array
if we pull data from your database it will typically be
in the form of a multi-dimensional array.
<?php
class foo extends CI_Controller {
public function index()
{
$data[’Books’] = array(’POEAA’, ’TDD’, ’Clean C’);
$data[’title’] = "Title";
$data[’heading’] = "Heading";
$this->load->view(’view’, $data);
}
}
in view
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
<h3>My Books List</h3>
<ul>
<?php foreach ($Books as $item):?>
<li><?php echo $item;?></li>
<?php endforeach;?>
</ul>
</body>
</html>
More Learning
NOTE:
There is a third optional parameter lets you change the behavior of the method so that it returns data as a string rather
than sending it to your browser.The default behavior is false, which sends it to your browser. Remember to
assign it to a variable if you want the data returned:
$string = $this->load->view(’view’, ’’, TRUE);
Above will not solve your problem directly but definetly help in understanding concepts.

Callback function in igniter datatables is not working

I am using igniter datatables in my code for datatables with server side processing.My code is like :
public function datatable()
{
$this->datatables->select("
insight_worksheet.id,
insight_worksheet.workingDate,
insight_worksheet.reason,
...
insight_worksheet.worksheet_status
")
->from("insight_worksheet")
->edit_column('Actions', '$1', 'callback_test(insight_worksheet.id,insight_worksheet.worksheet_status)')
...
->join("insight_status","status.id=worksheet.status","left");
echo $this->datatables->generate();
}
public function test($id,$worksheetStatus){
return "srimanta";
}
in my view page for Actions column direct string callback_test(insight_worksheet.id,insight_worksheet.worksheet_status)
is showing instead of actual work whereas for other columns, showing exact data.
For time being I put two functions in my controller class.
Could you please let me know the issue in my code?
Thanks in advance.
Try adding the callback function test in a helper file.
Your model file:
public function datatable()
{
$this->datatables->select("
insight_worksheet.id,
insight_worksheet.workingDate,
insight_worksheet.reason,
...
insight_worksheet.worksheet_status
")
->from("insight_worksheet")
->edit_column('Actions', '$1', 'test(insight_worksheet.id,insight_worksheet.worksheet_status)')
...
->join("insight_status","status.id=worksheet.status","left");
echo $this->datatables->generate();
}
your helper file:
public function test($id,$worksheetStatus){
return "srimanta";
}

cant get passed parameter by url in php

please help me, this is simple thing but I don't know why this still keep error for an hour,
on my view I've got :
<a href="admin/editProduct?idd=$id">
on my controller that directed from above :
public function editProduct(){
$data["id"] = $_GET['idd'];
$data["produk"] = $this->model_get->get_data_list(2);
//this below doesn't work either, i just want to past the parameter to my model
//$data["produk"] = $this->model_get->get_data_list($_GET['idd']);
$this->adminHeader();
$this->load->view("adminPages/editProduct", $data);
$this->adminFooter();
}
I can not use the array id. It keeps telling me undefined variable idd.
I don't know what to do anymore, please anyone help!
I am using Codeigniter framework
Change your view as:
<a href="admin/editProduct/<?php echo $id;?>">
And in the controller, either get the id as parameter,
public function editProduct($id) {
}
or as uri segment
public function editProduct() {
$id = $this->uri->segment(3);
}
Change your link (in view) with this
<a href="admin/editProduct/$id">
And change your controller as
public function editProduct($id) {
}
Then user $id inside your controller
Make the href link as follows:
...
And edit the controller like this:
public function editProduct($id){
...
$this->model_get->get_data_list($id);
}
Where $id will be the passed $id.
make
try this this works fine
public function editProduct()
{
$id=$this->uri->segment(3);
$data["produk"] = $this->model_get->get_data_list($id);
$this->adminHeader();
$this->load->view("adminPages/editProduct", $data);
$this->adminFooter();
}

calling two classes functions to one sorted output

im surfing in index.php file and My code is this:
index.php =
require("template.php"); // the file with the template of the site
$title="Home";
$phead='';
$html->htmlhead();
$htmlside="";
$html->htmlside();
require("file2.php"); // a file with class $queans and function question()
$htmlbody = $queans->questions();
$html->htmlbody($htmlbody);
$htmlfoot="";
$html->htmlfoot();
template.php = contain class $html and all it functions that i wrote at the previous file. and the spific proflem with the htmlbody function:
//all the class plugin
//in this specific function i wrote
$html->htmlbody($htmlbody){
echo '<div id="s">'.$htmlbody.'</div>';
}
file2.php =
$queans = new ques;
class ques{
public function questions(){
echo 'test';
}
}
at the end it shows me the output of $queans->questions() before the output of function questions() and the output is like:
test
<div id="s">
</div>
In your file2.php you have to return 'test' instead of echoing it.

PHP Vars From Included Bootstrap Not Showing Up in View

I have created my own little PHP framework for fun, however, I am having trouble passing variables from bootstrap to the views....
if I put an echo,print_r,var_dump my target variable in the bootstrap, the output is displayed in the browser before the tag... yet the target var in bootstrap.php is not available in the view, it is coming up as "" even though at the top of the page it is being output correctly....
Somethings I noticed from similar questions:
- The target variable is not being over written
- The include target path is correct and the file exists
- The file is only being included one time (include_once is only fired once)
Any ideas are greatly appreciated, I am pulling my hair out over here lol...
Source Code
https://gist.github.com/jeffreyroberts/f330ad4a164adda221aa
If you just want to display your site name, I think you can use a constant like that :
define('SITE_NAME', "Jeff's Site");
And then display it in your index.tpl :
<?php echo SITE_NAME; ?>
Or, you can send your variables to the view by extending a little bit your JLR_Core_Views :
class JLR_Core_Views
{
private $data;
public function loadView($templatePath, $data = array())
{
$this->data = $data;
$templatePath = JLR_ROOT . '/webroot/' . $templateName . '.tpl';
if(file_exists($templatePath)) {
// Yes, I know about the vuln here, this is just an example;
ob_start();
include_once $templatePath;
return ob_get_clean();
}
}
function __get($name)
{
return (isset($this->data[$name]))
? $this->data[$name]
: null;
}
}
Then, you can call your template like that :
$view = new JLR_Core_Views();
$view->loadView("index", array("sitename" => "Jeff's Site"));
And here is your index.tpl :
<?php echo $this->siteName; ?>
Below is another example of what you can do.
First, you create this class in order to store all the variables you want :
<?php
class JLR_Repository {
private static $data = array();
public function set($name, $value) {
self::$data[$name] = $value;
}
public function get($name) {
return (isset(self::$data[$name]))
? self::$data[$name]
: null;
}
}
?>
Then, when you want to store something in it :
JLR_Repository::set("sitename", "Jeff's Site");
And in your index.tpl :
<?php echo JLR_Repository::get("sitename"); ?>
try using the 'global' keyword - http://php.net/manual/en/language.variables.scope.php

Categories