From 44f5c73111e1ff03085d8a12755ce7bacc5ec93d Mon Sep 17 00:00:00 2001 From: djagya <danil.kabluk@gmail.com> Date: Sat, 15 Feb 2014 12:08:10 +0100 Subject: [PATCH] #2436 override the function `getAttributeLabel` in `BaseActiveRecord` to receive label of the attribute, which looks like `relatedMode.attribute`, from the related model --- framework/CHANGELOG.md | 1 + framework/db/BaseActiveRecord.php | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index c693cfc..44f7964 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -3,6 +3,7 @@ Yii Framework 2 Change Log 2.0.0 beta under development ---------------------------- +- Enh #2436: Label of the attribute, which looks like `relatedModel.attribute`, will be received from the related model if it available (djagya) - Bug #1265: AssetController does not override 'js' and 'css' for compressed bundles (klimov-paul) - Bug #1326: The `visible` setting for `DetailView` doesn't work as expected (qiangxue) - Bug #1412: `FileValidator` and `ImageValidator` still trigger `uploadRequired` error in some case when `skipOnEmpty` is true and no upload is provided (qiangxue) diff --git a/framework/db/BaseActiveRecord.php b/framework/db/BaseActiveRecord.php index f48ef4a..2613fb7 100644 --- a/framework/db/BaseActiveRecord.php +++ b/framework/db/BaseActiveRecord.php @@ -8,6 +8,7 @@ namespace yii\db; +use yii\base\Exception; use yii\base\InvalidConfigException; use yii\base\Model; use yii\base\InvalidParamException; @@ -1286,4 +1287,41 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface return false; } } + + /** + * Returns the text label for the specified attribute. + * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model. + * @param string $attribute the attribute name + * @return string the attribute label + * @see generateAttributeLabel() + * @see attributeLabels() + */ + public function getAttributeLabel($attribute) + { + $labels = $this->attributeLabels(); + if (isset($labels[$attribute])) { + return ($labels[$attribute]); + } elseif(strpos($attribute, '.')) { + $attributeParts = explode('.', $attribute); + $neededAttribute = array_pop($attributeParts); + + $relatedModel = $this; + foreach ($attributeParts as $relationName) { + try { + $relation = $relatedModel->getRelation($relationName); + } catch (InvalidParamException $e) { + return $this->generateAttributeLabel($attribute); + } + + $relatedModel = new $relation->modelClass; + } + + $labels = $relatedModel->attributeLabels(); + if (isset($labels[$neededAttribute])) { + return $labels[$neededAttribute]; + } + } + + return $this->generateAttributeLabel($attribute); + } } -- libgit2 0.27.1