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.
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);?>
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);?>
?>
<?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.