Yii2:如何控制允许用户查看哪些属性?

时间:2017-07-25 08:41:10

标签: php model yii2 attributes yii2-model

我想知道最佳方法是控制给定用户允许哪些模型属性查看

要控制允许哪些属性修改我当然使用scenarios,但有时应允许他们查看不允许修改的属性,所以我不能只使用相同的属性列表。

我想在中心点控制它,所以最好在模型中我猜。

采用这种方法的最佳方法是什么,或Yii的方法是什么?

1 个答案:

答案 0 :(得分:0)

我在想我需要类似scenarios的东西所以,基于这个想法,我现在尝试制作一个解决方案,在我的模型上创建一个名为viewable的方法,它返回一个列表对于模型的当前场景应该可见的属性。例如:

public function viewable() {
    $scenario = $this->getScenario();

    if ($scenario == self::SCENARIO_DEFAULT) {
        return [];

    } elseif ($scenario == self::SCENARIO_EV_ADMIN) {
        return $this->attributes();  //admin is allowed to see all attributes on the model

    } elseif ($scenario == self::SCENARIO_EV_ORGANIZER_INSERT || $scenario == self::SCENARIO_EV_ORGANIZER_UPDATE) {
        $attributes = $this->activeAttributes();  //use list of attributes they can edit as the basis for attributes they can view
        array_push($attributes, 'ev_approved', 'ev_status');  //add a few more they are allowed to view
        return $attributes;

    } else {
        return [];

    }
}

然后,例如。在GridViewDetailView中,我通过帮助程序传递列/属性列表,该帮助程序将过滤掉viewable未返回的任何属性。例如:

    'attributes' => MyHelper::filterAttributes([
        'eventID',
        [
            'attribute' => 'organizerID',
            'value' => \app\models\Organizer::findOne($model->organizerID)['org_name'],
        ],
        'ev_name',
        ....
    ], $model->viewable()),

我的助手方法是这样的:

public static function filterAttributes($all_attributes, $attributes_to_keep) {
    $output = [];
    foreach ($all_attributes as $value) {
        if (is_string($value)) {
            $colon = strpos($value, ':');
            if ($colon === false) {
                $name = $value;
            } else {
                $name = substr($value, 0, $colon);
            }
        } elseif (is_array($value)) {
            if ($value['attribute']) {
                $name = $value['attribute'];
            } elseif ($value['class']) {
                // always leave special entries intact (eg. class=yii\grid\ActionColumn)
                $output[] = $value;
                continue;
            } else {
                new UserException('Attributes name not found when filtering attributes.');
            }
        } else {
            new UserException('Invalid value for filtering attributes.');
        }

        if (in_array($name, $attributes_to_keep)) {
            $output[] = $value;
        }
    }
    return $output;
}

在create.php / update.php(或实际上是_form.php)中,我这样做:

$editAttribs = $model->activeAttributes();
$viewAttribs = $model->viewable();

....

if (in_array('organizerID', $viewAttribs)) {
    echo $form->field($model, 'organizerID')->textInput(['disabled' => !in_array('organizerID', $editAttribs) ]);
}

....

欢迎反馈!