How to assign unique id attribute to each table ro

2019-05-30 04:06发布

问题:

I am attempting to assign a unique id to each table row in Yii's CGridView.

Preferably something like $data->id from the database table.

I have been unsuccessful at adding an id attribute to each rendered <tr>.

Any suggestions would be most appreciated.

回答1:

CGridView have an option called 'rowHtmlOptionsExpression' , you can declare like the followings to assign row an id

'rowHtmlOptionsExpression' => 'array("id"=>$data->id)',

It's better than hacking into 'rowCssClassExpression'

Good luck !



回答2:

Modern solution (since Yii 1.1.13)

This is now possible to do using the rowHtmlOptionsExpression attribute, which allows assigning arbitrary HTML attributes to each rendered table row. For example:

'rowHtmlOptionsExpression' => '["id" => $data->id]'

Original answer (earlier versions)

Not directly possible because CGridView does not support it, but there are a couple of straightforward solutions that you can try.

Subclass CGridView (good)

Simply create your own class MyGridView extends CGridView and override the renderTableRow method to spit out ids on every row. Have a look at the stock implementation, which does for the class attribute exactly what you 'd like to do for the id attribute.

Use a CSS class instead (not so good)

Speaking of class attributes, the rowCssClassExpression property can be used to dynamically generate classes out of the box. IMHO this is a bad workaround, but it's there.



回答3:

You could extend CGridView to add that functionality.

or be a bit hacky with rowCssClassExpression.

'rowCssClassExpression' => '\'" data-id="\' . $data->rowID'


回答4:

Try the information I posted here: How to set key value in CGrideView when grid is populated from table-view

In essence, as long as your dataprovider to the CGridview provides the data->id in a form that it understands, it will auto handle the $data->id stuff for you automatically so that it's easily available to javascript.



回答5:

CGridView.rowHtmlOptionsExpression is undefined

I don't think that we can use rowHtmlOptionsExpression



标签: yii cgridview