Define Variable in controller to us that variable in view

Hi experts,

I want to define variable (for my case $val) in controller, which will be used in view form. This created variable data will be bind with the model to save the data in the database.

Want to use it like…

<?= $form->field($model, ‘val’)->hiddenInput([‘value’=>’$val’])->label(false);?>

Can you please help me how to define the variable in controller?

Thanks in advance.

Regards,

Sid

Add $val to $model’s class:




class YourModel extends ActiveRecord {

// 1

public $val;

// 2

public function rules() {

    return [

        ['val', 'integer-or-whatever-else']

    ];

}



here is an example with data sent down to view from controller.


<?php


// example with default SiteController ...

class SiteController extends Controller {

    public function actionIndex()

    {

        return $this->render('view_name', [

            // other data you need to send to your view ...

            'val' => 'value goes here',

        ]);

    }

}


// your view 

<?= $form->field($model, 'val')->hiddenInput(['value'=> $val])->label(false);?>

A better approach would be to set the value in your model, I would suggest you set the value in your model with default value.




<?php


// your model might contain default value for $val

class User extends Model {

    public $val = 'default_value';

}


// you view code

<?= $form->field($model, 'val')->hiddenInput()->label(false);?>

Hello experts,

Thanks for the replies.

I would like to set some variable function in $val. like rand().

Can you guide me how and where to set it.

Regards,

Sid

Hi, if you want to implement some random value in $val i think you can just set it in your model class. Something like this.

Then you can call it from your view.




<?php


// Model code

class User extends Model {

    public $val;

}


public function getVal(){

$this->val = rand();


return $this->val;

}


// View code


<?= $form->field($model, 'val')->hiddenInput(['value' => $model->getVal()])->label(false);?>


?>



simplest possible solution is


<?php


// example with default SiteController ...

class SiteController extends Controller {

    public function actionIndex()

    {

        return $this->render('view_name', [

            // other data you need to send to your view ...

            'val' => rand(),

        ]);

    }

}


// your view 

<?= $form->field($model, 'val')->hiddenInput(['value'=> $val])->label(false);?>

you can’t put function as value of your properties




<?php


class User extends Model {

    public $val = rand();

}


?>

Please note it is always a good idea to read about general concepts of php and programming before you jump into a framework.

You’re right, was trying to think the simplest solution for the problem here, sorry about that. Will edit my answer to not mislead people here.

Thanks team. Appreciate your efforts for the solution and the idea.

Regards,

Sid