Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get attribute label in Yii2 ActiveRecord

How to get attribute label in Yii2?

I found this function getAttributeLabel() here in Yii2 doc, I am using it in a controller. But it's throwing an error:

Call to undefined function app\controllers\getAttributeLabel()

like image 502
Piyush Avatar asked Nov 16 '15 09:11

Piyush


People also ask

What is an active record in Yii?

The Yii documentation summarizes this concisely: An Active Record class is associated with a database table, an Active Record instance corresponds to a row of that table, and an attribute of an Active Record instance represents the value of a particular column in that row.

What is yiidbactiverecord class?

Class yiidbActiveRecord. ActiveRecord is the base class for classes representing relational data in terms of objects. Active Record implements the Active Record design pattern. The premise behind Active Record is that an individual yiidbActiveRecord object is associated with a specific row in a database table.

Should I redeclare an attribute in active record?

Yii automatically defines an attribute in Active Record for every column of the associated table. You should NOT redeclare any of the attributes.

What makes Yii so secure?

The integration of the Active Record patterning into Yii is a great strength of the framework, but common to most frameworks such as Ruby on Rails. This abstraction from models to database tables allows the framework to perform the heavy lifting of security everywhere, e.g. breaking down SQL injection queries.


3 Answers

$task = new Task();

//to get single attribute label
$label = $task->getAttributeLabel('task_title');

//to get all attribute label
$labels = $task->attributeLabels();
like image 56
Prahlad Avatar answered Oct 07 '22 12:10

Prahlad


try this

$model          =   new ModelName();
print_r($model->attributeLabels());

if you use the above code you can get an array containing all attribute labels of a model

like image 40
Bloodhound Avatar answered Oct 07 '22 12:10

Bloodhound


Since Yii 2.0.13 ActiveRecord implements StaticInstanceInterface, so you can use instance() to get static instance of model. Using it should be cleaner and more efficient that manually creating instance of model to use its non-static methods.

$singleLabel = MyModel::instance()->getAttributeLabel('my_attribute');

$allLabels = MyModel::instance()->attributeLabels();
like image 20
rob006 Avatar answered Oct 07 '22 13:10

rob006