2017-10-19 9 views
0

私の残りのアプリケーションのシナリオを使用して、私のアクションに余分なフィールドを追加したいと思います。これは私が

コントローラのアクションYii2セットのシナリオが機能していません

$model =(new Job(['scenario' => Job::SCENARIO_MORE]))->findOne(['id'=>$id]); 
if ($model){ 
    return $model; 
} 


モデルコード

const SCENARIO_LESS = 'index'; 
const SCENARIO_MORE = 'view'; 

public function scenarios() 
{ 
    return [ 
     self::SCENARIO_LESS => ['field1', 'field2'], 
     self::SCENARIO_MORE => ['field1', 'field2', 'field3'], 
    ]; 
} 

しかし、まだそれがデフォルトフィールド、任意のアイデアを発生なし変更を返してやったことありますか?

答えて

2

私はシナリオだけで、主に検証し、大規模な属性の割り当てで使用されるテーブル

シナリオ機能にデータを挿入する前にデータを検証するために使用と思います。ただし、他の目的に使用することはできます。たとえば、現在のシナリオに基づいて属性ラベルを異なる方法で宣言することができます。

しかし、あなたが特定のフィールドをしたい場合は、モデル内のfieldsメソッドを使用する必要があります。

// explicitly list every field, best used when you want to make sure the changes 
// in your DB table or model attributes do not cause your field changes (to keep API backward compatibility). 
public function fields() 
{ 
    return [ 
     // field name is the same as the attribute name 
     'id', 

     // field name is "email", the corresponding attribute name is "email_address" 
     'email' => 'email_address', 

     // field name is "name", its value is defined by a PHP callback 
     'name' => function() { 
      return $this->first_name . ' ' . $this->last_name; 
     }, 
    ]; 
} 

// filter out some fields, best used when you want to inherit the parent implementation 
// and blacklist some sensitive fields. 
public function fields() 
{ 
    $fields = parent::fields(); 

    // remove fields that contain sensitive information 
    unset($fields['auth_key'], $fields['password_hash'], $fields['password_reset_token']); 

    return $fields; 
} 

参照:http://www.yiiframework.com/doc-2.0/guide-structure-models.html#fields

+0

は、私が(フィールド内のフィールドをフィルタリングするためのシナリオを使用することができます)機能? –

+1

なぜそれを試してみませんか?しかし私はそうは思わない。 'toArray()'関数を使ってモデルの配列を与え、 'unset'関数を使って特定のフィールドを削除することです。 –

関連する問題