Yii $form->textfield, how to set a default value?

2019-04-03 14:28发布

So I am fiddling with the Yii Framework and in one of the views, specifically the create form, I am trying to give one of my textfields a default value. Therefore when I go onto my create page the values are already preloaded on the form.

Here is my current code

<div class="row">
    <?php echo $form->labelEx($model,'teamlead'); ?>
    <?php echo $form->textField($model,'teamlead',array('size'=>50,'maxlength'=>50,'value'=>Yii::app()->user->getUsername(),'disabled'=>'disabled')); ?>
    <?php echo $form->error($model,'teamlead'); ?>
</div>

When I press create, Yii gives me an error telling me that there textField is empty? Not sure what else I can do other than set the value. Am I also suppose to set the model attributes?

标签: yii
7条回答
Bombasti
2楼-- · 2019-04-03 14:39

It works on my end:

<?= $form->field($model, 'some_field')->textInput(['readonly' => true, 'value' => 'Your Value']) ?>
查看更多
Bombasti
3楼-- · 2019-04-03 14:50
<div class="row">
    <?php echo $form->labelEx($model,'teamlead'); ?>
    <?php echo $form->textField($model,'teamlead',array('readonly'=>'true',size'=>50,'maxlength'=>50,'value'=>Yii::app()->user->getUsername(),'disabled'=>'disabled')); ?>
    <?php echo $form->error($model,'teamlead'); ?>
</div>

put array('readonly'=>'true') in your coding it will work

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-04-03 14:52

before you field description add this:

<?php
$model->teamlead='my default value';
?>
查看更多
再贱就再见
5楼-- · 2019-04-03 14:54

Here is my code that I am sending fixed value into database and show that value readonly.

<?php echo $form->textField($model,'pp_status', array('value'=>'Open', 'readonly' => 'true')); ?>
查看更多
淡お忘
6楼-- · 2019-04-03 14:56

Always, is a good idea deal with data (defaul values, change after something happening, data treatment, etc) on the model class.

If you're getting the value from after initialize the model, the best way is to use the method init().

But, if you want to change, or define a default value after load data from the database, you can use the method afterFind()

For example:

public function afterFind(){
    $this->localdate = date("Y-m-d");
    parent::afterFind();
}

This link has a lot of usefull information about these methods: http://www.yiiframework.com/doc/guide/1.1/en/database.ar#customization

查看更多
Lonely孤独者°
7楼-- · 2019-04-03 14:56

I believe the MVC way to do this is to place your default value either in your Model:

class MyModel extends \yii\db\ActiveRecord
{
    public $teamlead = 'my default value';
    ....
}

Or in your controller:

class MyModelController extends Controller
{
    public function actionCreate()
    {
        $model = new MyModel ();
        $model->teamlead = 'my default value';
        ...
    }
}
查看更多
登录 后发表回答