Now I have created a test function in component and registered in the config->main.php. But when I am calling that function in the view file, it is generating the value but not inside the input field. Hence the data is not getting saved.
<?php
namespace frontend\components;
use Yii;
use yii\base\Component;
class RandomGenerator extends \yii\web\View
{
var $ran;
public function randomnumber()
{
{
$ran=rand(100,199);
}
echo $ran;
}
}
?>
first you need to access your component by name you used in your config file, also use of var keyword is deprecated use public,private,protected modifiers to declare class properties, here is an example of your code with some improvements.
<?php
// component file
namespace frontend\components;
use Yii;
use yii\base\Component;
class RandomGenerator extends Component
{
// you can configure your component using the
// properties declared publicly
public $min = 100;
public $max = 200;
public function getNumber()
{
return rand($this->min, $this->max);
}
}
// config/web.php
"components" => [
// ...
"randomGenerator" => [
"class" => "frontend\components\RandomGenerator",
"min" => 100, // overwrite the min value
"max" => 300 // overwrite the max value
]
// ...
]
// update your view code like so
<?= $form->field($model, 'value1')->textInput(['readonly' => true, 'value' => Yii::$app->randomGenerator->getNumber()]); ?>
Just for curiosity, can we put conditional value for this $max and $min?? Like if it is condition "A" then $max and $ min is 100 to 199 respectively or if it is condition "B" then $max and $min values is 200 to 250 respectively?
indeed conditionals can be used to determine the value of min and max but you can’t put them directly with properties use the init function which is fired when the component registers with yii
<?php
// component file
namespace frontend\components;
use Yii;
use yii\base\Component;
class RandomGenerator extends Component
{
// you can configure your component using the
// properties declared publicly
public $min = 100;
public $max = 200;
public function init()
{
if ($a === true) {
$this->min = 0;
$this->max = 100;
}
if ($b === true) {
$this->min = 100;
$this->max = 1000;
}
}
public function getNumber()
{
return rand($this->min, $this->max);
}
}
In conditional situation as explained by you, can I fetch value from a table for $a, $b…The values in the table saved as number range like "10-15" etc.
If it is possible how to fetch it to get the output?