codeigniter table array variable not defined - php

This should be a simple passing an array to a view. The controller is set to pull all data from the table. I have initialized the table library and loaded the model code with the $this->load->model(array('Account'). I have full crud methods built.
I am getting a variable undefined on my view page.
Controller code is:
public function index(){
$this->load->library('table');
$children = array();
$this->load->model(array('Account'));
$children = $this->Account->get(); //retrieves all the records in the database
foreach ($children as $child){
$account = new Account();
$account->load($account->id);
$children[] = array(
$account->id,
$account->familyName,
$account->addr1,
$account->city,
$account->state,
$account->zip,
$account->phone1,
$account->email,
$account->parent_only,
);
}
$this->load->view('main_view');
$this->load->view('body_content_ma', array(
'body_content_ma' => $children,
));
}
On the view page I get an error that says undefined variable children. What do you think I am missing here:
View code is:
<?php
$this->table->set_heading('ID', 'Family Name', 'City', 'State', 'Zip', 'Phone', 'Email', 'Parent only Pickup');
echo $this->table->generate($children);
?>
ANSWER:
This is the coding that finally worked.
I had to go back through it a few times to get it what was missing.
public function index(){
$this->load->library('table');
$children = array();
$this->load->model(array('Account'));
$account = $this->Account->get(); //retrieves all the records in the database
foreach ($account as $c){
$account = new Account();
$account->load($account->id);
$children[] = array(
$c->id,
$c->familyName,
$c->addr1,
$c->city,
$c->state,
$c->zip,
$c->phone1,
$c->email,
$c->parent_only,
);
}
//echo '<tt><pre>' . var_export($children, TRUE) . '</pre></tt>';
$this->load->view('main_view');
$this->load->view('body_content_ma', array(
'body_content_ma' => $children
));
}
I had a feeling that I was using $children to many times and was overwriting the variable. I was right. Once I declared the variable. I should not have used it again.
When I reassigned the variable $children to $children = $this->Account->get();
I think I effectively overwrote the array that was declared the line before. So even though the array was filled the array reference was destroyed.
I did use the $body_content_ma in the view code to generate the table.
Everything is being rendered now.
On to pagination!

just simple things you are missing $children variable is mapped to $body_content_ma
just replace $children to $body_content_ma .
echo $this->table->generate($children);
replace by
echo $this->table->generate($body_content_ma );

you can use this code.. hope will be working for you.
public function index(){
$this->load->library('table');
$children = array();
$this->load->model(array('Account'));
$data['children'] = $this->Account->get(); //retrieves all the records in the database
$this->load->view('main_view');
$this->load->view('body_content_ma',$data));
}
in view you can use $children as a array to print the value.

This would be my function;
public function index()
{
$this->load->library('table');
$this->load->model('Account_model');
$data['children'] = $this->Account_model->get();
foreach ($data['children'] as $child)
{
// Your foreach code...
}
$this->load->view('main_view');
$this->load->view('body_content_ma', $data);
}

Your view:
<?php
$this->table->set_heading('ID',
'Family Name',
'City',
'State',
'Zip',
'Phone',
'Email',
'Parent only Pickup');
echo $this->table->generate($body_content_ma);
?>
Explanation:
You are passsing body_content_ma from your controller to your view and not children hence giving you an undefined error.
Edit:
Below is the format of the array to generate rows of the table.
The array should consist of array of rows.
$data = array(
array('Name', 'Color', 'Size'),
array('Fred', 'Blue', 'Small'),
array('Mary', 'Red', 'Large'),
array('John', 'Green', 'Medium')
);
echo $this->table->generate($data);
Documentation: http://ellislab.com/codeigniter/user-guide/libraries/table.html

Related

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 } ?>

Laravel get and paginate same data

I am using Laravel for controller and blade file for a webpage. My code is something like:
PropertiesController
$properties = Property::where('status', 1);
$properties = $properties->orderBy('properties.created_at', 'DESC')->paginate(8);
return view('properties.index')->with('properties', $properties);
in index.blade.php
#foreach ($properties as $property)
<div class="geo">
<span class="lat">{{ $property->title }}</span>,
<span class="lng">{{ $property->description }}</span>
</div>
what I want to achieve is to get categories w.r.t. counts along with properties, for that, I am doing
$properties = Property::where('status', 1);
$categories = array();
if (is_null($req->c)) {
$search = $properties;
foreach (Category::all() as $category) {
array_push(
$categories,
array(
'id' => $category->id,
'name' => $category->category,
'counts' => count($search->where('properties.category', $category->id)->get()),
)
);
}
}
$properties = $properties->orderBy('properties.created_at', 'DESC')->paginate(8);
return view('properties.index')->with('properties', $properties)->with('categories', $categories);
$search = $properties; and
'counts' => count($search->where('properties.category', $category->id)->get()),
with this it gives me
Trying to get property of non-object
<span class="lat"><?php echo e($property->title); ?></span>,
What I think is you want to pass your data to blade view and get counts of categorized data with each category... For that, you can use duplicated functions to count your data separately. e.g.:
public function properties() {
$properties = Property::where('status', 1);
$categories = array();
foreach (Category::all() as $category) {
$count = $this->count($category->id);
array_push(
$categories,
array(
'id' => $category->id,
'name' => $category->category,
'counts' => $count,
)
);
}
$properties = $properties->orderBy('properties.created_at', 'DESC')->paginate(8);
return view('properties.index')->with('properties', $properties)->with('categories', $categories);
}
public function count($id) {
$count = count(Property::where('category_id', $id)); // or any variable you are using to connect categories table with
return $count;
}
$count = $this->count($category->id);
This is the line which did the trick.
If the relationships are made in the models you should only use with () in this way.
This is how the controller should be.
$properties = Property::where('status', 1)->with('category')->orderBy('properties.created_at', 'DESC')->paginate(8);
return view('properties.index', compact('propierties'));
This will give you the list of Properties next to the assigned category.
But if you need to list the categories and have in each category the properties you must do this.
$categories = Category::with('properties')->paginate(8);
return view('properties.index', compact('categories'));

YIi PHP - Output array with a foreach loop

I'm trying to return a navigation menu using Yii PHP framework, but my controller is only outputting the first item in the array, here's my code. Note that this pattern isn't using the traditional MVC, the model i'm asking data for is being displayed site-wide, not directly to its's controller->view.
Model - get data;
//output pages for getPagesMenuItems() in base controller
public function getAllPages(){
$criteria = new CDbCriteria();
$criteria->condition = "visible = 1";
return Pages::model()->findAll($criteria);
}
Base controller in components
public $pagesMenuItems = array();
$this->pagesMenuItems = $this->getPagesMenuItems();
protected function getPagesMenuItems() {
//Non admin users - links to pages
if (Yii::app()->user->isGuest){
$rows = Pages::getAllPages();
foreach($rows as $row) {
return array(
//$row->id , $row->title , $row->guid , $row->visible
array('label' => $row->title, 'icon' => 'fa fa-times', 'url' => array('/admin/pages/view/id/' . $row->id)),
'---',
);
}
// return array();
}
else {}
}
And this is the view in the main.php
$this->widget('booster.widgets.TbMenu', array(
'items' => $this->pagesMenuItems,
'id' => 'pagesNav'
));
I know the issue is packaging the array in the foreach loop, as i've tested the output of the model and all data is correct
Can anyone see where i'm going wrong in my controller?
Thanks
change getPagesMenuItems function as below:
protected function getPagesMenuItems() {
//Non admin users - links to pages
$data = array();
if (Yii::app()->user->isGuest){
$rows = Pages::getAllPages();
foreach($rows as $row) {
$data[] = array('label' => $row->title, 'icon' => 'fa fa-times', 'url' => array('/admin/pages/view/id/' . $row->id));
}
}
else {}
return $data;
}

How to in view pass array data to controller with model(in one atribute) Yii

It is my view in Yii framework. i wanna pass from here array data to controller with only one model attribute or just array without model. how to do it?
<?php $i = 1; foreach ($images as $image):
CHtml::activeLabel($model, 'remove', array('for'=>'rm_'.$image))
CHtml::activeCheckBox($model,'remove',array('name'=>'Obyavlenie[remove]', 'id'=>'rm_'.$image)) // remove is array(attribute) to pass
CHtml::link($image, 'name', array()),$image);
in model
class Obyavlenie extends CActiveRecord
{
public $remove;// should get array from view
Try this
<?php echo CHtml::activeCheckBox($model,'remove',array('name'=>'Obyavlenie[remove]['.$image‌​.']', 'id'=>'rm_'.$image)) ?>
Use CheckBoxList for multiple values.
In view:
// 1. Set data list
$list = array();
foreach ($images as $image):
$list[ $image ] = CHtml::link($image,'#'); // Change [ $image ] unique identificator to determine image you need
endforeach;
// 2. Output checkboxes
CHtml::activeCheckBoxList($model,'remove',$list,array(
'template' => '{input} {label}'
));
In action:
$model = new Obyavlenie('removeImages');
if ( isset( $_POST['Obyavlenie'] ) ) {
$model->attributes = $_POST['Obyavlenie']
}
In model:
class Obyavlenie extends CActiveRecord {
public $remove;
public function rules(){
return array(
// ...
array( 'remove', 'type', 'type' => 'array', 'on' => 'removeImages' )
);
}
// other model's methods
P.S. Obyavlenie -> Advert

How do you remove specific fields from all entities of a record set in Lithium?

I am using MySQL as the database connection adapter for all my models. I have a downloads model and controller with an index function that renders either an HTML table or a CSV file depending on the type passed from the request. I also have a CSV media type to handle an array of data, which is working as expected (outputs array keys as headers then array values for each row of data).
I wish to do the same find query but then remove ID fields from the record set if a CSV file is going to be rendered. You'll notice that the download ID is being fetched even though it is not in the fields array, so simply changing the fields array based on the request type will not work.
I have tried the following in the index action of my downloads controller:
<?php
namespace app\controllers;
use app\models\Downloads;
class DownloadsController extends \lithium\action\Controller {
public function index() {
// Dynamic conditions
$conditions = array(...);
$downloads = Downloads::find('all', array(
'fields' => array('user_id', 'Surveys.name'),
'conditions' => $conditions,
'with' => 'Surveys',
'order' => array('created' => 'desc')
));
if ($this->request->params['type'] == 'csv') {
$downloads->each(function ($download) {
// THIS DOES NOT WORK
unset($download->id, $download->user_id);
// I HAVE TRIED THIS HERE AND THE ID FIELDS STILL EXIST
// var_dump($download->data());
// exit;
return $download;
});
return $this->render(array('csv' => $downloads->to('array')));
}
return compact('downloads');
}
}
?>
I thought there was an __unset() magic method on the entity object that would be called when you call the standard PHP unset() function on an entity's field.
It would be great if there was a $recordSet->removeField('field') function, but I can not find one.
Any help would be greatly appreciated.
Perhaps you should do $downloads = $downloads->to('array');, iterate the array with a for loop, remove those fields from each row, then return that array. If you have to do this same thing for a lot of actions, you could setup a custom Media handler that could alter the data without needing logic for it in your controller.
Take a look at this example in the Lithium Media class unit test.
You can also avoid having much logic for it in your controller at all through the use of a custom handler. This example also auto-generates a header row from the keys in your data.
In config/bootstrap/media.php:
Media::type('csv', 'application/csv', array(
'encode' => function($data, $handler, $response) {
$request = $handler['request'];
$privateKeys = null;
if ($request->privateKeys) {
$privateKeys = array_fill_keys($request->privateKeys, true);
}
// assuming your csv data is the first key in
// the template data and the first row keys names
// can be used as headers
$data = current($data);
$row = (array) current($data);
if ($privateKeys) {
$row = array_diff_key($row, $privateKeys);
}
$headers = array_keys($row);
ob_start();
$out = fopen('php://output', 'w');
fputcsv($out, $headers);
foreach ($data as $record) {
if (!is_array($record)) {
$record = (array) $record;
}
if ($privateKeys) {
$record = array_diff_key($record, $privateKeys);
}
fputcsv($out, $record);
}
fclose($out);
return ob_get_clean();
}
));
Your controller:
<?php
namespace app\controllers;
use app\models\Downloads;
class DownloadsController extends \lithium\action\Controller {
public function index() {
$this->request->privateKeys = array('id', 'user_id');
// Dynamic conditions
$conditions = array(...);
$downloads = Downloads::find('all', array(
'fields' => array('user_id', 'Surveys.name'),
'conditions' => $conditions,
'with' => 'Surveys',
'order' => array('created' => 'desc')
));
return compact('downloads');
}
}
?>
Why not then just dynamically set your $fields array?
public function index() {
$type = $this->request->params['type'];
//Exclude `user_id` if request type is CSV
$fields = $type == 'csv' ? array('Surveys.name') : array('user_id', 'Surveys.name');
$conditions = array(...);
$with = array('Surveys');
$order = array('created' => 'desc');
$downloads = Downloads::find('all', compact('conditions', 'fields', 'with', 'order'));
//Return different render type if CSV
return $type == 'csv' ? $this->render(array('csv' => $downloads->data())) : compact('downloads');
}
You can see in this example how I send the array for your CSV handler, otherwise it's the $downloads RecordSet object that goes to the view.

Categories