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()
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.
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.
Yii automatically defines an attribute in Active Record for every column of the associated table. You should NOT redeclare any of the attributes.
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.
$task = new Task();
//to get single attribute label
$label = $task->getAttributeLabel('task_title');
//to get all attribute label
$labels = $task->attributeLabels();
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With