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

后端 未结 7 1459
心在旅途
心在旅途 2021-02-12 11:32

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

相关标签:
7条回答
  • 2021-02-12 11:38

    before you field description add this:

    <?php
    $model->teamlead='my default value';
    ?>
    
    0 讨论(0)
  • 2021-02-12 11:38

    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

    0 讨论(0)
  • 2021-02-12 11:41

    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')); ?>
    
    0 讨论(0)
  • 2021-02-12 11:43

    Please use array('readonly' => true) instead of disabled.

    0 讨论(0)
  • 2021-02-12 11:51

    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';
            ...
        }
    }
    
    0 讨论(0)
  • <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

    0 讨论(0)
提交回复
热议问题