YII CListView How to add id to itemwrapper - php

In CListView there is a property called "itemsCssClass" which basically adds HTML class attribute to the Itemwrapper.
What if I like to add an ID or any other htmlOptions how will I do it on that wrapper..?
My code is :
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$model->search(),
'viewData'=>array('x'=>''),
'itemView'=>'_classifieds',
'id'=>'boa_ads',
'itemsCssClass'=>'test'
));
This code will produce this HTML:
<div id="boa_ads" class="list-view">
<div class="summary">Displaying 1-4 of 4 results.</div>
<div class="items"><!-- HERE ID LIKE TO ADD AN ID-->
----ITEMS GOES HERE ----
</div>
</div>
</div>
Thanks for your help in advance

From the Yii's source:
public function renderItems()
{
echo CHtml::openTag($this->itemsTagName,array('class'=>$this->itemsCssClass))."\n";
.....
echo CHtml::closeTag($this->itemsTagName);
}
I just see class attribute is passed to the itemsTagName so you probably have to extend CListView to do it.
You can create a CCustomListView class (inside application/widgets folder) which extends from CListView and overwrite renderItems() function. For example:
<?php
Yii::import("zii.widgets.CListView");
class CCustomListView extends CListView
{
public $itemsHtmlOptions;
/**
* Renders the data item list.
*/
public function renderItems()
{
echo CHtml::openTag($this->itemsTagName, array_merge(array('class'=>$this->itemsCssClass), $this->itemsHtmlOptions))."\n";
$data=$this->dataProvider->getData();
if(($n=count($data))>0)
{
$owner=$this->getOwner();
$viewFile=$owner->getViewFile($this->itemView);
$j=0;
foreach($data as $i=>$item)
{
$data=$this->viewData;
$data['index']=$i;
$data['data']=$item;
$data['widget']=$this;
$owner->renderFile($viewFile,$data);
if($j++ < $n-1)
echo $this->separator;
}
}
else
$this->renderEmptyText();
echo CHtml::closeTag($this->itemsTagName);
}
}
In your view, you can use it like:
<?php $this->widget('application.widgets.CCustomListView', array(
'dataProvider'=> 'your_data_provider',
'itemsHtmlOptions' => array('style' => 'color:blue', 'id' => 'your_id'),
'itemView'=>'your_item_view',
'template'=>'your_template',
)); ?>
So the style which in itemsHtmlOptions will be applied for the listview.
This link is also useful for you: How to extend CListView in order to remove extra yii added markup?

Related

ZF2 add params to setPartial submenu

I use this partial to generate my submenu.
<?php foreach ($this->container as $page): ?>
<?php foreach ($page->getPages() as $child): ?>
<a href="<?php echo $child->getHref(); ?>" class="list-group-item">
<?php echo $this->translate($child->getLabel()); ?>
</a>
<?php endforeach; ?>
<?php endforeach; ?>
Which is called like this:
$this->navigation('navigation')->menu()->setPartial('partial/submenu')->render();
But when i render the menu the "$child->getHref()" renders the url without the needed "slug/id" parameter.
I tried to create the url with "$this->url()" in ZF1 you could pass the params in an array to the partial but in ZF2 that doesn't seem to work anymore.
Can anybody tell me how to add the params to the menu urls?
Thanks in advance!
PS!
I'm not referring to $this->Partial, i'm talking about $this->navigation('navigation')->menu()->setPartial('partial/submenu')->render() which apparently doesn't support a param array.
If I'm understanding your question, yes, you can pass params to partials. Example:
<?php echo $this->partial('partial.phtml', array(
'from' => 'Team Framework',
'subject' => 'view partials')); ?>
See http://framework.zend.com/manual/2.3/en/modules/zend.view.helpers.partial.html
I'm not sure this completely solves your issue, since you are not showing what the menu helper is. Is it your own view helper? Are you saying that setPartial method only accepts one argument?
All that said, have you considered Spiffy Navigation?
https://github.com/spiffyjr/spiffy-navigation
It's been sometime since this question was asked, however today I came across the same problem (using version 2.4).
If you have a segment route to be included within the menu that requires some parameters there is no way to pass these through to the navigation's view partial helper.
The change I've made allows a ViewModel instance to be passed to the menu navigation helper's setPartial() method. This view model will be the context for the navigation's partial template rendering; therefore we can use it to set the variables we need for the route creation and fetch them just like within other views using $this->variableName.
The change requires you to extend the Menu helper (or which ever navigation helper requires it).
namespace Foo\Navigation;
use Zend\Navigation\AbstractContainer;
use Zend\View\Model\ViewModel;
class Menu extends \Zend\View\Helper\Navigation\Menu
{
public function renderPartial($container = null, $partial = null)
{
if (null == $container) {
$container = $this->getContainer();
}
if ($container && $partial instanceof ViewModel) {
$partial->setVariable('container', $container);
}
return parent::renderPartial($container, $partial);
}
public function setPartial($partial)
{
if ($partial instanceof ViewModel) {
$this->partial = $partial;
} else {
parent::setPartial($partial);
}
return $this;
}
}
Because this extends the default implementation of the helper updated configuration is required in module.config.php to ensure the extend class is loaded.
'navigation_helpers' => [
'invokables' => [
'Menu' => 'Foo\Navigation\Menu',
],
],
The menu helper will then accept a view model instance.
$viewModel = new \Zend\View\Model\ViewModel;
$viewModel->setTemplate('path/to/partial/template')
->setVariable('id', $foo->getId());
echo $this->navigation()
->menu()
->setPartial($viewModel)
->render();
The only change in the actual partial script will require you to create the URL's using the URL view helper.
foreach ($container as $page) {
//...
$href = $this->url($page->getRoute(), ['id' => $this->id]);
//...
}

How to save input in yii to database

I have this code Im trying to save the content and the title from a form I made..It has an id that autoincrement the id number adds in the database but the title and the content isn't/cant be save in the database. Can you please check my code if I've done something wrong? or what I'm lacking at.
Here is my model ContentForm.php
<?php
class ContentForm extends CActiveRecord{
public $content;
public $title;
public function tableName(){
return 'tbl_content';
}
public function attributeLabels()
{
return array(
'contentid' => 'contentid',
'content' => 'content',
'title' => 'title',
// 'email' => 'Email',
// 'usrtype' => 'Usrtype',
);
}
Here is my view content.php
<div>
<p>User: <a href="viewuserpost">
<?php
echo Yii::app()->session['nameuser'];
?>
</a>
</p>
</div>
<h1>Content</h1>
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
Title:
<div class="row">
<?php
echo $form->textfield($model,'title');
?>
</div>
</br>
Body:
<div class="row">
<?php
echo $form->textArea($model,'content',array('rows'=>16,'cols'=>110));
?>
</div>
<div class="row buttons">
<?php
echo CHtml::submitButton($model->isNewRecord? 'Create':'Save');
?>
</div>
<?php $this->endWidget(); ?>
and here is my content action in my sitecontroller.php
public function actionContent(){
$model=new ContentForm;
if(isset($_POST['ContentForm'])) {
$model->attributes=$_POST['ContentForm'];
if($model->save())
$this->redirect(array('content','contentid'=>$model->contentid));
$this->redirect(array('content','title'=>$model->title));
$this->redirect(array('content','content'=>$model->content));
}
$this->render('content',array('model'=>$model));
}
Please help.
Remove
public $content;
public $title;
from your class.
Yii uses PHP magic methods. And when you add attributes to your class, PHP doesn't call them but references to your explicitly written attributes.
Moreover, you should add some validation, if you use $model->attributes=$_POST['ContentForm'];. Another variant is to use unsecure $model->setAttributes($_POST[ContentForm], false) where false tells Yii to set all attributes, not only that are considered safe.
Note, that attributes is not real Model attribute, this is virtual attribute accessed through magic methods.
Also, you don't need three redirects. This is HTTP redirect to other page. This time, you just should just specify route to model view action and its parameter that is id, for example. Like this $this->redirect(array('content/view','id'=>$model->contentid));.
Of course, simplest way for you is to create new model and controller with actions using Gii.
you may missed rules , add this in your model ContentForm.php
public function rules()
{
return array(
array('content,title', 'safe'),
);
}
For more about model validation
http://www.yiiframework.com/wiki/56/reference-model-rules-validation/

YII language selector doesn't make the postback to controller

I'm making a language selector and followed this wiki. I can implement the widget, but when I try the dropdown it doesn't make the postback. For the controller I have the idea that the controller should be: components/Controller.php in stead of components/MyController.php. But anyways both don't work. Does anyone know what to do here? I'm missing something about the essentials of catching a postback here i think..
Controller (components/controller.php):
function init()
{
parent::init();
$app = Yii::app();
if (isset($_POST['_lang']))
{
$app->language = $_POST['_lang'];
$app->session['_lang'] = $app->language;
}
else if (isset($app->session['_lang']))
{
$app->language = $app->session['_lang'];
}
Yii::app()->session['_lang'] = 'anders';
}
widget class (components/LangBox.php):
class LangBox extends CWidget
{
public function run()
{
$currentLang = Yii::app()->language;
$this->render('langBox', array('currentLang' => $currentLang));
}
}
widget view (components/views/langBox.php)
<?php echo CHtml::form(); ?>
<div id="langdrop">
<?php echo CHtml::dropDownList('_lang', $currentLang, array(
'en_us' => 'English', 'is_is' => 'Icelandic'), array('submit' => '')); ?>
</div>
<?php echo CHtml::endForm(); ?>
I am sure your code works ok, but are you actually submitting the form? You should really have a jquery that detects when the dropdown changed and submits it to the server and refreshes the page. Everything else is sound.
I have no idea what 'submit'=>'' does.

DropDownList effects a ClistView in Yii

I am still very new to this Yii framework, and I would like assistance with this code. I currently manage to get a dropdownlist dependent on another dropdownlist but I can't seem to get the dropdownlist to effect what gets displayed in the ClistView.
profile Controller
/* add a team message submitted by the coach of the team */
public function actionAddTeamMessage($id)
{
/* check if team and message aren't null */
if(isset($_POST['teamId']['addTeamMessage']))
{
try
{
/* creates a new message */
$teamModel = new TeamMessage;
$teamModel->teamId = $_POST['teamId'];
$teamModel->content = $_POST['addTeamMessage'];
$teamModel->sendTime = new CDbExpression('NOW()');
$teamModel->save();
}
catch(Exception $e)
{
echo "Unable to save.";
}
}
/* render the profile page for the current user */
$user=User::model()->findByPk($id);
$this->render('profile', array(
'model' => $user));
}
/* will handle functionality for the user dropdownlist ajax
* under contructions
*/
public function actionDisplayMessage()
{
$data = TeamMessage::model()->findAll('teamId=:teamId', array(
':teamId'=>(int) $_POST['teamId']
)
);
$data=CHtml::listData($data,'id', 'content');
echo "<option value=''>Select Message</option>";
foreach($data as $value=>$content)
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($content),true);
//TODO still being tested.
/* for ClistView still debugging */
/*$dataProvider=new CActiveDataProvider('Player', array(
'criteria'=>array(
'condition'=>'teamId=:teamId',
)));*/
}
View Profile
<!-- Would allow user to access specific team messages and control how much gets display.
still under construction. -->
<div class="row">
<?php
echo CHtml::dropDownList("teamId", 'id', Chtml::listData($model->memberOfTeams, 'id', 'teamName'),array(
'empty'=>'Select Team',
'ajax'=>array(
'type'=>'POST', // request type
'url'=>CController::createUrl('DisplayMessage'),
'update'=>'#teamMessages', // selector to update
'data'=>array('teamId'=>'js:this.value'),
)
)
);
?>
<?php
echo CHtml::dropDownList('teamMessages','',array(),array('empty'=>'Select Message'));
/*$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_viewTeamMessage',
'id'=>'ajaxListView',
));*/
?>
</div>
As you can see in the cListView. I was debating on creating a _viewTeamMessage which will display the team message + sendtime. But I realize, I wouldn't be able to pass a dataprovider without re rendering the page, and i am trying to avoid heading into that direction.
You could pull your Team messges out into a partial view and then just use a render partial to render just the messages into your page usig Ajax. If the partial view is named _teamMessages.php it would look something like this (untested):
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_viewTeamMessage',
'id'=>'ajaxListView',
));
Then you modify your profile view to look like:
<!-- Would allow user to access specific team messages and control how much gets display.
still under construction. -->
<div class="row">
<?php
echo CHtml::dropDownList("teamId", 'id', Chtml::listData($model->memberOfTeams, 'id', 'teamName'),array(
'empty'=>'Select Team',
'ajax'=>array(
'type'=>'POST', // request type
'url'=>CController::createUrl('DisplayMessage'),
'update'=>'.team-messages', // selector to update
'data'=>array('teamId'=>'js:this.value'),
)
)
);
?>
<div class="team-messages">
<?php
$this->renderPartial('_teamMessages',
array('dataProvider'=>$dataProvider))
?>
</div>
</div>
Then finally you change your controller to something like this:
public function actionDisplayMessage()
{
/* REMOVE
$data = TeamMessage::model()->findAll('teamId=:teamId', array(
':teamId'=>(int) $_POST['teamId']
)
);
$data=CHtml::listData($data,'id', 'content');
echo "<option value=''>Select Message</option>";
foreach($data as $value=>$content)
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($content),true);
*/
// still being tested.
$dataProvider=new CActiveDataProvider('Player', array(
'criteria'=>array(
'condition'=>'teamId=(int) $_POST['teamId']',
)));
$this->renderPartial('_teamMessages', array('dataProvider'=>$dataProvider);
}
this should just cause the message widget to be recreated instead of the whole page.

How did $data extracted from dataprovider when using clistview widget?

In yii framework demos, there is an blog demo. In this blog demo a Post controller has two different actions: index and view.
/**
* Lists all models.
*/
public function actionIndex()
{
$criteria=new CDbCriteria(array(
'condition'=>'status='.Post::STATUS_PUBLISHED,
'order'=>'update_time DESC',
'with'=>'commentCount',
));
if(isset($_GET['tag']))
$criteria->addSearchCondition('tags',$_GET['tag']);
$dataProvider=new CActiveDataProvider('Post', array(
'pagination'=>array(
'pageSize'=>Yii::app()->params['postsPerPage'],
),
'criteria'=>$criteria,
));
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Displays a particular model.
*/
public function actionView()
{
$post=$this->loadModel();
$comment=$this->newComment($post);
$this->render('view',array(
'model'=>$post,
'comment'=>$comment,
));
}
and index view is:
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'template'=>"{items}\n{pager}",
)); ?>
and view view is:
<?php $this->renderPartial('_view', array(
'data'=>$model,
)); ?>
but both index and view use _view:
<div class="author">
posted by <?php echo $data->author->username . ' on ' . date('F j, Y',$data->create_time); ?>
</div>
<div class="content">
<?php
$this->beginWidget('CMarkdown', array('purifyOutput'=>true));
echo $data->content;
$this->endWidget();
?>
</div>
here is my question: I can understand the view assign the 'data' => $model, so in _view, $data is valid. In index action, the widget clistview is applied, but i cannot understand where is $data variable being set? I know the $data presents the current post(from dataprovider). I just cannot figure out how and where did yii did this?
Thanks for any help.
The above code first creates a data provider for the Post ActiveRecord class. It then uses CListView to display every data item as returned by the data provider. The display is done via the partial view named '_post'. This partial view will be rendered once for every data item. In the view, one can access the current data item via variable $data.
By using the itemView property of CListView which is used for rendering each data item. This property value will be passed as the first parameter to CController property renderpartial to render each data item.
public string renderPartial(string $view, array $data=NULL, boolean $return=false, boolean $processOutput=false)
public function renderPartial($view,$data=null,$return=false,$processOutput=false)
{
if(($viewFile=$this->getViewFile($view))!==false)
{
$output=$this->renderFile($viewFile,$data,true);
if($processOutput)
$output=$this->processOutput($output);
if($return)
return $output;
else
echo $output;
}
else
throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
array('{controller}'=>get_class($this), '{view}'=>$view)));
}
Renders a view.
If $data is an associative array, it will be extracted as PHP variables and made available to the script The named view refers to a PHP script .the Script Which is resolved via getViewFile Used in the renderPartial method the script for getViewFile as shown below
public function getViewFile($viewName)
{
if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
return $viewFile;
$moduleViewPath=$basePath=Yii::app()->getViewPath();
if(($module=$this->getModule())!==null)
$moduleViewPath=$module->getViewPath();
return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
}
Looks for the view file according to the given view name.
renderItems is the abstract method defined in CBaseListView ClassFile
/**
* Renders the data items for the view.
* Each item is corresponding to a single data model instance.
* Child classes should override this method to provide the actual item rendering logic.
*/
abstract public function renderItems();
And This Method is Overriden by ClistView Class
CListView widget loops thru $dataProvider, and for each item it does something like that:
$this->renderPartial($itemView, array(
'data'=>$model,
));
Where $itemView is view file set in CListView config.
And that's it.
Edit: To clarify of how CListView iterates over dataprovider items: it is defined in CListView::renderItems, in short, the most important parts are:
// Get dataprovider data as array
$data=$this->dataProvider->getData();
...
// Get viewfile
$viewFile=$owner->getViewFile($this->itemView);
...
// Loop thru $data items
foreach($data as $i=>$item)
{
...
// Here data is assigned from dataprovider item
$data['data']=$item;
...
// Render view file
$owner->renderFile($viewFile,$data);
}

Categories