passing variable from controller to the view in api rest codeigniter - php

I have two controllers, in the first which extends CI_Controller where I load my views ( represents my home page), in the second which extends REST_controller I have a class where I load my models and functions to get my arrays from sql requests to send them to my views.
So I'm not that I understood well how rest works but I want to know if my architecture is good like I explained.
I want also to know how I can display simple variables using rest, I mean if for example I have a function in my model such :
public function nb_bananas()
{
$query = $this->db->query('SELECT count(*) as nb
FROM bananas
');
if ($query->num_rows() > 0)
{
return $query->result_array();
}else{
return NULL;
}
}
before using rest I used to get nb of bananas in controller such as :
$data['nb_bananas]=$this->MyModel->nb_bananas();
and I display the number of bananas in my view such as :
<?php echo $nb_bananas[0]['nb'] ?>
My question is, now when I'm using rest I should get my return sql request in the controler such as :
public function nb_bananas_get(){
$nb_bananas=$this->MyModel->nb_bananas();
if ($nb_bananas){
$this->response($nb_bananas,REST_Controller::HTTP_OK);
}
else{$this->response([
'status' => FALSE,
'message' => 'No users were found'
], REST_Controller::HTTP_NOT_FOUND);}
Is that correct ?
And what is the simple way display just the nb_bananas in my view without using any buttun like in a Dashboard?
Or maybe even if in restful I can use the old method to pass my variable to the views ?
Thank you for your answers.

Related

very confused with passing data array from controller to view in laravel or calling it from the view

ok I have my route to my controller (for future crud maybe angular use)
public function Dashboard_Clicks()
{
$DBClicks = DB::table('TotalClicks')->select('Total_Clicks')->get();
return view::('dashboard.pages')->with('$DBClicks', Total_Clicks);
do I use view composer? or another clean simple way to call this in?
}
this has one result a number 45454
I want to be able to get this result in my view like so.
<h1 class="clicks"><strong>{{ $DBClicks->Total_Clicks }} </strong> </h1>
You can try this: (Laravel 5)
return view('dashboard.pages', ['Total_Clicks' => $DBClicks]);
As far as I can recall there are two ways of passing data from controller to views first is compacting the variable in your controller and it will available as it is in your view. An example for the same is following:
$variable = 'somedata';
$array = ['some' => 'data'];
return view('viewName', compact('variable', 'array'));
//now in your view you can access {{$variable}} and #foreach($array as $something)
Second is with :
return view('viewName')->with(['first_var' => $variable, 'first_array' => $array])
//now in your view you can access {{$first_var}} and #foreach($first_array as $array)

Laravel 4.2 is_online article

I'm confronted to a little problem, i try to add a method to show only online article, but i want to know how do implement this method.
In my DB i have a row is_online (Int) for 0=> offline, 1=>online, how do implement that for my view.
in my models with
public function isonline(){}
or in my PostController in my request of post find.
And after need to add in my admin panel a check box in Post create to change the status off article (online or offline-draft).
You should use Eloquent scope in your code by creating online scope in your model.
public function scopeOnline($query)
{
return $query->where('is_online', 1);
}
Draft posts
public function scopeDrafts($query)
{
return $query->where('is_online', 0);
}
Then in your code you can simply use it like this.
$onlinePosts = Post::online()->get();
$draftPosts = Post::drafts()->get();
You just need to find all records who have flag is_online = 1.
You can write one method in your PostController like
Public function getOnlineRecords{
$records = YourModel::where('is_online','=',1)->get();
return View::make('your_view_path',['records'=>$records]);
}
In your View file, you need to write:-
{{ Form::checkbox('your_field_name', 'value', true) }}
If you want to default the value as checked, pass true as the third argument.

Generate multiple result in codeigniter

Currently I am working on one Web-based software which creates results automatically in codeigniter. I create modules like add student, add marks & generate mark sheet. here in generate marksheet i created individual marksheet but now I want to generate code for generate marksheet on one button click.
For that i use file_get_content(), curl(), fopen() but this all showing blank page if file_get_content("http://127.0.0.1/exam/admission/forms/showResult/41/2/1")
shows individual students result i want to show it in page
Here is My controller code
class forms extends CI_Controller {
function __construct() {
parent::__construct();
$this->admin_layout->setLayout('template/layout_admission');
$session = $this->session->userdata('admin_session');
if (empty($session) || $session->type != 'admission') {
$this->session->set_flashdata('error', 'Login First');
redirect(base_url() . 'login', 'refresh');
}
function printDoc(){
$siteaddressAPI = "http://127.0.0.1/exam/admission/forms/showResult/41/2/1";
$data = file_get_contents($siteaddressAPI);
echo $data;
}
}
Your Question does not explain exactly what you need.!!! Better you can give your sample code with expected result.
Still I have a solution which might help you in some way.
You can use view template to generate mark-sheet code. For Example:
$mark_sheets = array();
foreach($all_students_data as $student_data){
$mark_sheets[] = $this -> load -> view('marksheet_template', $student_data, TRUE);
}
Here $this -> load -> view() with third parameter TRUE will return generated html code and then store it in mark_sheets array.
By this way, you can access all your mark-sheets from $mark_sheets array.

Zend MVC: one call from controller to model or more calls for differents results?

i need differents results from a model but i don't understand if it is correct make a single call and leave to model all the work or make more calls and collect the result to pass to the view when tables aren't joined or when i need fetch one row from a table and differents rows from others.
First example (more calls, collect and send to view):
CONTROLLER
// call functions of model
$modelName = new Application_Model_DbTable_ModelName();
$rs1 = $modelName->getTest($var);
$rs2 = $modelName->getTest2($var2);
// collect data
$pippo = $rs1->pippo;
if ($rs2->pluto == 'test') {
$pluto = 'ok';
} else {
$pluto = 'ko';
}
// send to view
$this->view->pippo = $pippo;
$this->view->pluto = $pluto;
MODEL
public function getTest($var) {
...
select from db...
return $result;
...
}
public function getTest2($var) {
...
select from db...
return $result;
...
}
Second example (one call, model collect all data, return to controller and send to view):
CONTROLLER
// call one function of model
$modelName = new Application_Model_DbTable_ModelName();
$rs = $modelName->getTest($var);
MODEL
public function getTest($var) {
...
select from db...
if ($result > 0) {
call other function
call other function
collect data
return $result;
...
}
Thanks
There's no one correct answer to this question, but in general, you should endeavor to keep your business logic in one place. Think of it as, "thin controller, thick model." I.e., keep the controllers as small and simple as possible and put all the business logic in the models.
There seems to be a few questions here:
But if i don't need to interact with db and i need only a simply
function is better put that function in model? For example:
CONTROLLER:
public function printAction() {
$data = $this->getRequest()->getPost();
$label = "blablabla";
$this->view->label = $label;
}
first, in the context of Zend Framework this particular example doesn't make much sense. The whole point of the controller is to populate the view template. However, I do get the idea. I would point you to Action Helpers and View helpers as a means to address your concerns. You can always add a utility class to your library for those pieces of code that don't seem to fit anywhere else.
Action Helpers typically are employed to encapsulate controller code that may be repetitive or reusable. They can be as simple or as complex as required, here is a simple example:
class Controller_Action_Helper_Login extends Zend_Controller_Action_Helper_Abstract
{
/**
* #return \Application_Form_Login
*/
public function direct()
{
$form = new Application_Form_Login();
$form->setAction('/index/login');
return $form;
}
}
//add the helper path to the stack in the application.ini
resources.frontController.actionhelperpaths.Controller_Action_Helper = APPLICATION_PATH "/../library/Controller/Action/Helper"
//the helper is called in the controller
$this->_helper->login();
a View helper does the same thing for the view templates:
class Zend_View_Helper_PadId extends Zend_View_Helper_Abstract
{
/**
* add leading zeros to value
* #param type $id
* #return string
*/
public function padId($id)
{
return str_pad($id, 5, 0, STR_PAD_LEFT);
}
}
//in this example the helper path is added to the stack from the boostrap.php
protected function _initView()
{
//Initialize view
$view = new Zend_View();
//add custom view helper path
$view->addHelperPath('/../library/View/Helper');
//truncated for brevity
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(
'ViewRenderer');
$viewRenderer->setView($view);
//Return it, so that it can be stored by the bootstrap
return $view;
}
//and to use the helper in the view template
//any.phtml
<?php echo $this->padId($this->id) ?>
i need differents results from a model but i don't understand if it is
correct make a single call and leave to model all the work or make
more calls and collect the result to pass to the view when tables
aren't joined or when i need fetch one row from a table and differents
rows from others.
This question is more about structure then about correctness.
You can interact with your database table models in Action and View helpers for simple/repetitive queries if you need to, however most developers might frown on this approach as being difficult to maintain or just ugly.
Many people seem to favor Doctrine or Propel to help them manage their database needs.
At this point I like to roll my own and currently favor domain models and data mappers, not an end all be all pattern, but seems to be appropriate to your question.
This is not a simple suggestion to implement for the first time, however i found two articles helpful to get started:
http://phpmaster.com/building-a-domain-model/
http://phpmaster.com/integrating-the-data-mappers/
and if you really want to get into it try:
http://survivethedeepend.com/
I hope this answers at least a part of your questions.

CodeIgniter get_where

I’m attempting to use get_where to grab a list of all database records where the owner is equal to the logged in user.
This is my function in my controller;
function files()
{
$owner = $this->auth->get_user();
$this->db->get_where('files', array('owner =' => '$owner'))->result();
}
And in my view I have the following;
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
When I try accessing the view, I get the error :
Fatal error: Call to a member function result() on a non-object in /views/account/files.php on line 1.
Wondered if anyone had any ideas of what might be up with this?
Thanks
CodeIgniter is a framework based on MVC principles. As a result, you would usually separate application logic, data abstraction and "output" into their respective areas for CodeIgniter use. In this case: controllers, models and views.
Just for reference, you should usually have you "data" code as a model function, in this case the get_where functionality. I highly suggest you read through the provided User Guide to get to grips with CodeIgniter, it should hold your hand through most steps. See: Table of Contents (top right).
TL;DR
To solve your problem you need to make sure that you pass controller variables through to your view:
function files()
{
$owner = $this->auth->get_user();
$data['files'] = $this->db->get_where('files', array('owner =' => '$owner'))->result();
$this->load->view('name_of_my_view', $data);
}
And then make sure to use the correct variable in your view:
<?php foreach($files as $row): ?>
<span><?=$row['name']; ?></span>
<?php endforeach; ?>
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Remove the result function like so.
<?php foreach($query as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Btw. It's a much better idea to test the query for a result before you return it.
function files()
{
$owner = $this->auth->get_user();
$query = $this->db->get_where('files', array('owner =' => $owner))->result();
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;
}
public function get_records(){
return $this->db->get_where('table_name', array('column_name' => value))->result();
}
This is how you can return data from database using get_where() method.
All querying should be performed in the Model.
Processing logic in the View should be kept to an absolute minimum. If you need to use some basic looping or conditionals, okay, but nearly all data preparation should be done before the View.
By single quoting your $owner variable, you convert it to a literal string -- in other words, it is rendered as a dollar sign followed by five letters which is certainly not what you want.
The default comparison of codeigniter's where methods is =, so you don't need to declare the equals sign.
I don't know which Auth library you are using, so I'll go out on a limb and assume that get_user() returns an object -- of which you wish to access the id of the current user. This will require ->id chained to the end of the method call to access the id property.
Now, let's re-script your MVC architecture.
The story starts in the controller. You aren't passing any data in, so its duties are:
Load the model (if it isn't already loaded)
Call the model method and pass the owner id as a parameter.
Load the view and pass the model's returned result set as a parameter.
*Notice that there is no querying and no displaying of content.
Controller: (no single-use variables)
public function files() {
$this->load->model('Files_model');
$this->load->view(
'user_files',
['files' => $this->Files_model->Files($this->auth->get_user()->id)]
);
}
Alternatively, you can write your controller with single-use variables if you prefer the declarative benefits / readability.
public function files() {
$this->load->model('Files_model');
$userId = $this->auth->get_user()->id;
$data['files'] = $this->Files_model->Files($userId);
$this->load->view('user_files', $data);
}
Model: (parameters are passed-in, result sets are returned)
public function Files($userId) {
return $this->db->get_where('files', ['owner' => $userId])->result();
}
In the above snippet, the generated query will be:
SELECT * FROM files WHERE owner = $userId
The result set (assuming the query suits the db table schema) will be an empty array if no qualifying results or an indexed array of objects. Either way, the return value will be an array.
In the final step, the view will receive the populated result set as $files (the variable is named by the associative first-level key that was declared in the view loading method).
View:
<?php
foreach ($files as $file) {
echo "<span>{$file->name}</span>";
}
The { and } are not essential, I just prefer it for readability in my IDE.
To sum it all up, the data flows like this:
Controller -> Model -> Controller -> View
Only the model does database interactions.
Only the view prints to screen.

Categories