0
votes

In Yii2 i had a controller that generate a gridview(kartik) with some dynamic columns, i have to make filters for this columns, but to do a filter for a column I need a variable with the name of that column in searchModel and an entry in the array of rules with that name too, how to do that being that my columns are dynamically generated in the controller?

i've been tried use a array as a variable, with keys as a name to the columns, but i dont know how to use arrays in searchModel with rules.

searchModel.php

...
public $loja_cnpj;
public $loja_nome;
public $forn_status;
//  public $forn10420318; <- this need to be generate dynamically

public function rules()
{
   return [
      [['id', 'empresa_id', 'grupo_loja_id', 'status', 'numero_checkout', 
      'numero_funcionarios', 'loja_id'], 'integer'],
      // [['nome', 'telefone', 'empresa','grupo_loja', 'email', 'cnpj', 
      'loja_nome', 'loja_cnpj', 'forn10420318'], 'safe'],
      [['nome', 'telefone', 'empresa','grupo_loja', 'email', 'cnpj', 
      'loja_nome', 'loja_cnpj', 'forn_status["forn10420318"]'], 'safe'],
      [['area_venda', 'tamanho_loja'], 'number'],
      ['forn_status', 'each', 'rule' => ['safe']], <- i'm stuck here
      ];
...

controller.php

...
$searchModel   = new LojaFornecedorSearch();
...
foreach($queryFornecedor as $fornecedor){
         $colTemp = array([
            'attribute' => 'forn'.$fornecedor->id,
            'label'     => 'forn'.$fornecedor->id,
            'value'     => function($model)use($fornecedor)... <- dynamic columns array to be inserted in gridView

i'm stuck at this point.

2

2 Answers

0
votes

You may use DynamicModel for this scenario. First, extend LojaFornecedorSearch from DynamicModel:

class LojaFornecedorSearch extends \yii\base\DynamicModel {
    // ...
}

Then you can define attributes dynamically in this way:

$searchModel = new LojaFornecedorSearch();
// ...
foreach ($queryFornecedor as $fornecedor) {
    $searchModel->defineAttribute('forn' . $fornecedor->id);
    $searchModel->addRule('forn' . $fornecedor->id, 'safe');
    // ...
}
-1
votes

welcome to stackoverflow

I think you can do it rules() and adding __construct() method.

see blow:

function __construct(){
   // setting attributes
   $this->{$varname};
}

and change rules to :

public function rules()
{
    $default_rules = [
        [['id', 'empresa_id', 'grupo_loja_id', 'status', 'numero_checkout',
            'numero_funcionarios', 'loja_id'], 'integer'],
        // and whatever rule you have
    ];
    $new_rules = [
        ['Your_dynamic_var', 'safe']
    ];
    return array_merge($default_rules,$new_rules);
}