Studying Programming Yii, I want to display the last 4 pages:
SiteController.php
public function actionStart()
{
$featured = Page::model()->findAllByAttributes(
array(),
$condition = 'featured = :featureId',
$params = array(
':featureId' => 1,
)
);
$this->render('/layouts/start/start', array('featured'=>$featured));
}
/layouts/start/start.php
<?php print_r($this->featured); ?>
The latter file does not display anything, and should be an array with the data, how do I get it?
$this->render('/layouts/start/start', array('featured'=>$featured));
Here, you are sending array(association array) of values to the View. You can access these values by calling the array Key.
So, your code should be
<?php echo print_r($featured); ?>
Another example.
$this->render('myView', array('myName'=>'Hearaman','myAge'=>25));
I'm sending my name and age to View. To show my name and age, i should call the keys
echo $myName;
echo $myAge;
Eliminate the $this for featured.
<?php echo print_r($featured, true); ?>
Related
Trying to produce a bulleted list from text field in MySQL - I have the bullets in the DB field : I'm pulling data into the array $products, I need the string in array to be formatted as a bullet list in the products $Keyfindings2 results
<?php
/* This controller renders the category pages */
class CategoryController{
public function handleRequest(){
$cat = Category::find(array('id'=>$_GET['category']));
if(empty($cat)){
throw new Exception("There is no such category!");
}
// Fetch all the categories:
$categories = Category::find();
// Fetch all the products in this category:
$products = Product::find(array('category'=>$_GET['category']));
// $categories and $products are both arrays with objects
$Keyfindings2 = explode('•', $products);
echo "<ul style=\' list-style-type:upper-roman;\'>\n";
foreach( $Keyfindings2 as $item )
{
echo "<li>$item</li><br />\n";
}
echo "</ul>";
render('category',array(
'title' => 'Browsing '.$cat[0]->name,
'categories' => $categories,
'products' => $Keyfindings2
));
}
}
?>
UPDATE: now getting 'undefined variable' in other part of code on line 1:
<li <?php echo ($active == $category->id ? 'data-theme="a"' : '') ?>>
<a href="?category=<?php echo $category->id?>" data-transition="fade">
<?php echo $category->name ?>
<span class="ui-li-count"><?php echo $category->contains?></span></a>
</li>
You problem is quite simple: you are using explode on the wrong thing.
If your code/comments is right $products is an array and you explode it. You probably have your PHP error level too low because this produce a PHP warning: PHP Warning: explode() expects parameter 2 to be string, array given in php shell code on line 1
So from there 2 solutions: either $products is an array of strings and you can do
function myExplode($product) {
return explode('•', $product);
}
$Keyfindings2 = array_map('myExplode', $products);
or $products is an array of objects (as your code comment suggests) and you go with:
function myExplode($product) {
// well actual the name of the field or method to call really depends on your
// code and there is no way we can tell it with what we have on your post
// so consider this an example
return explode('•', $product->productFieldContainingList);
}
$Keyfindings2 = array_map('myExplode', $products);
With either solution the goal is the same: to apply explode on the correct data, not on an array containing that data.
I have a problem in updating my model values, one of the model attributes is a number that is selected from a dropDownList, here is my code:
<?php $images = Homepage::model()->findAll();
if(!empty($images)){
$data = array();
$x = 1;
foreach ($images as $i){
array_push($data, $x);
$x++;
}
?>
<?php echo $form->labelEx($model,'order'); ?>
<?php echo $form->dropDownList($model, 'order', $data, array(
'empty'=>'Select image order',
'id'=>'order')); ?>
this dropDownList is containing the number of records of model (table) in the db, the problem is in the update function, for example: on the creation of (image 1) I selected 1 as the order value, then when I go to the update, I got the pre-selected option is 2 (which is the last value of the listData) instead of 1, so what is the error here ?
Im not a Yii expert but i think you are doing it wrong, Im using this code below and it works fine im getting the id from the database and showing it in the dropDown list, try it maybe it helps or check http://www.yiiframework.com/wiki/48/by-example-chtml/#hh5 ,
<?php echo $form->labelEx($model,'order_id'); ?>
<?php echo $form->dropDownList($model,'order_id',
CHtml::listData(Homepage::model()->findAll(),'order_id','order_id'),
array('empty'=>'--Select order --') ); ?>
You need to define the selected in the options
'options'=>array($model->id => array('selected'=>true))
Roughly your code will look like this now
echo $form->dropDownList($model, 'order', $data, array(
'empty'=>'Select image order',
'id'=>'order',
'options'=>array($model->id =>array('selected'=>true))
));
Give it a try this will help.
I think it might be with the $data variable.
In my experience with Yii, i always use associative array ($key=>$value) for dropdown
so maybe something like
$data = array('1'=>'Test', '2'=>'Test 2');
In this way, Test and Test 2 will be the values displayed on the dropdown itself and '1' and '2' will be the values stored in the $model and the database.
My code is pretty basic. I'm using an array to generate a datasheet for a product based on it's SKU and a filepath.
My array looks like this:
$a=array(
"/images/ManualSheets/factSheetCLASSIC.pdf"=>"KE800/6",
"/images/ManualSheets/factSheetMICRO.pdf"=>"KE800/12",
"/images/ManualSheets/factSheetSMALL.pdf"=>"KE4000/12",
"/images/ManualSheets/factSheetMEDIUM.pdf"=>"KE8000/12",
);
Where the first Key is the filepath, and the second Key is the SKU (as generated by the system) I then use an if/else to generate a button - so if a product is not in the array it returns a blank value and doesn't have a button which leads to nowhere
$factsheetweblink_url = array_search($product_sku,$a);
if ($factsheetweblink_url==false) {
echo " ";
}
else {
echo "<div class='productpagestockistBTN'>
<img src='/images/FactSheet_btn.png' >
</div>";
}
?>
This code works fine. The catch comes when I have products with different SKUs but the same datasheet file, (same brand and make but a different model). Currently I can only get it to work by uploading multiple copies of the datasheets with different names, but it's becoming a big waste of space.
I have tried using an array as a key to hold multiple values to the one key..
"/images/ManualSheets/factSheetMEDIUM.pdf"=> array("KE8000/12","KE7000/12"),
but it doesn't seem to be working... I'm not quite sure if I need to refine my if statement to search within the sub arrays as well or..?
Any help would be appreciated, thanks in advance.
You should use arrays like this:
$products = array(
0 => array(
"pdf" => "/images/ManualSheets/factSheetCLASSIC.pdf",
"skus" => array("KE800/6","KE900/6")
),
1 => array(
"pdf" => "/images/ManualSheets/factSheetCLASSIC3.pdf",
"skus" => array("KE100/6","KE200/6"))
);
This is because array_search returns just first row whit that key.
Then just do your own search function like:
function findBySku($items, $sku) {
$pdf = ""; // return empty if not found.
foreach($items as $row) {
if (in_array($sku, $row['skus'])) {
$pdf = $row['pdf'];
break;
}
}
return $pdf;
}
and call that function:
$pdf = findBySku($products, "some sku");
I have a table called Table, it has id and name as attributes.
For each entry in Table, I would like to generate a checkbox.
How can I do this?
I am using the Yii-Boostrap plugin, which I'm expecting I would need use something like this:
foreach(...)
echo $form->checkBoxRow($model, 'name');
Which I got from the Yii-Bootstrap Documentation.
Try this simple one
And in this for precheck to work just pass the array as second parameter
as shown below
<?$select=array('2','3');?>
<?php echo CHtml::checkBoxList(
'TableValues',
'$select',//you can pass the array here which you want to be pre checked
CHtml::listData(Table::model()->findAll(),'id','name'),
array('checkAll'=>'Select all tasks', 'checkAllLast'=>true)
); ?>
And you can get the selected checkbox values in the controller using
print_r($_POST['TableValues']);
UPDATED
For this the precheck to work u have to assign the array to the model attribute as shown below
<?php $model->modelAttributename=array('3','5')//respective checked values as of yours
<?php echo $form->checkBoxList(
$model,
'modelAttributename',
CHtml::listData(Table::model()->findAll(),'id','name'),
array('checkAll'=>'Select all tasks', 'checkAllLast'=>true)
); ?>
You should see your result array form sql query and see how to access any string you want from result array and then you create array of string that contain list of name.
e.g. your result query is $result["name"] = array("a","b","c");
<?php /** #var BootActiveForm $form */
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'horizontalForm',
'type'=>'horizontal',
));
?>
<fieldset>
<legend>Legend</legend>
<?php
$result["name"] = array("a","b","c");
echo $form->checkBoxListRow($model, 'checkboxes', $result["name"]);
?>
</fieldset>
Check this example:
Book Model:
'authors' => array(self::MANY_MANY, 'Author', 'authorbook(book_id,author_id)'),
Author Model:
'books' => array(self::MANY_MANY, 'Book', 'authorbook(author_id, book_id)'),
Checkbox List in form:
$books = CHtml::listData(Book::model()->findAll(), 'id', 'name');
$selected_keys = array_keys(CHtml::listData( $model->books, 'id' , 'id'));
echo CHtml::checkBoxList('Author[books][]', $selected_keys, $books);
I wrote a small piece to get a value from a database table according to the input user provides. Quickly here are the events:
User inputs number to an input and submit form
That data are supposed to call the controller, and then the controller have to match and grab relevant data from the database table, and pass it to the controller again.
Then the controller must pass it to the view, where another text input (readonly) picks up the data as the value.
But what I received was an error:
Message: Undefined variable: due_amount
Filename: main/new_payment.php
Line Number: 148
Line number 148 in new_payment.php is
);
in the View.
This is my Model:
function get_by_room_number($room_data) {
$this->db->select('due_amount');
$query = $this->db->get_where('rooms', array('room_number' => $room_data), 1);
if($query->num_rows()>0) {
foreach ($query->result() as $row) {
return $row->due_amount;
}
}
This is the Controller:
function search_by_number() {
$room_data = $this->input->post('room_number');
$due_amount = $this->payments_model->get_by_room_number($room_data);
$this->index();
}
This is the View: (new_payment.php)
<?php echo form_open('payments/search_by_number'); ?>
<?php $data = array(
'name' => 'total_amount',
'id' => 'appendedPrependedInput',
'class' => 'span2',
'value' => $due_amount
); // Line Number 148
echo form_input($data);
?>
<?php echo form_close(); ?>
Try like
$data['due_amount'] = $this->payments_model->get_by_room_number($room_data);
and try to sent it to view like
$this->load->view('view_file',$data);
and at your view file echo it like
echo $due_amount;
assuming that $data is the array that you are passing to your view from your controller function.You cont pass a variable from controller to view.You need to pass it through an array data and then you can get the variable with that variable name
You should assign due_amount to $data variable and pass it to view. Like this:
$data['room_data'] = $this->input->post('room_number');
$data['due_amount'] = $this->payments_model->get_by_room_number($data['room_data']);
$this->load->view('my_view', $data);
Then in view you could do:
print_r($room_data);
print_r($due_amount);
CodeIgniter User Guide might help you understand it better.