Adding an attribute for title to a yii widget
Posted: February 24, 2012 Filed under: Applications, Technical Notes, Yii | Tags: Computers, journal incubator, scaffolding, Tips, workflow manager, YII
The Yii file
by default uses the [
to display all examples of a given model. In the standard scaffolding produced by the
utility, this widget consists of references to attributes of the model without any further information (e.g. attribute names and the like):
<?php $this->widget('zii.widgets.CDetailView', array( 'data'=>$model, 'attributes'=>array( 'editorialInstance_id', 'journal.shortTitle', // a reference to a relational attribute 'type', 'LastNamesFirstName', // a reference to a compound attribute ),
In this minimalist form, yii will calculate an appropriate label for the attribute on the basis of the attribute name: so, for example, in this case, editorialInstance_id will be appear in the view labelled “Editorial Instance” because Yii understands camelCase naming conventions and knows to strip off _id (it’s that good!).
A problem with this, however, is that we also provide customised label names as part of the
method in our Model controller. Since that method allows arbitrary names, and since
attempts to calculate labels on the basis of the attribute name, it is highly likely that the labels for different attributes will get out of synch in different places in your site. To give an example: in this particular case, the model for editorialInstance might have defined the label for editorialInstance_id as “ID” rather than “Editorial Instance”: since
doesn’t check to see what you had on
in the model class, switching from an edit view to an index will mean that the label of the attribute switches.
Ideally what you want to do is keep
in synch automatically. I’m sure there must be a way of doing this. In the meantime, however, here’s how you can set an arbitrary label in the widget (I’ve used it on the first and last):
<?php $this->widget('zii.widgets.CDetailView', array( 'data'=>$model, 'attributes'=>array( array('value' => $model->editorialInstance_id, 'label' => 'ID'), 'journal.shortTitle', 'type', array('value' => $model->person->lastNameFirstNames, 'label' => 'Person'), ),