Ascending Form numbers in Yii

2020-03-31 04:11发布

问题:

In Yii I am doing a form in which the form has input fields for user details.I have made necessary input fields for all those fields.Where a user can submit all the values.Now I have a field where it will show the form number which will not be entered by user.It will be generated randomly with ascending order like for the 1st form it will be like this FORM:001, For the second form it will be like this FORM:002 and it will go on. Now I want that the form number will be like Form:001 so how to do that?HAny help and suggestions will be highly appriciable.

[UPDATED]

  <div class="row">
    <?php echo $form->labelEx($model,'id'); ?>
    <?php echo Yii::app()->db->getLastInsertId();?>
    <?php echo $form->error($model,'id'); ?>
  </div>

This is the code for view > _form.php file. and the result is ID 0

回答1:

What you need is either of the following:

$maxFormId= Yii::app()->db->createCommand()
->select('max(id) as max')
->from('tbl_yourtable')
->queryScalar();
$yourFormId = "Form:".($maxFormId+ 1);

or alternatively run the following after the insert, and only display the form id then:

$yourFormId = "Form:".Yii::app()->db->getLastInsertId();

UPDATE:

public function actionCreate()
    {
        $model=new YourModel;

        if(isset($_POST['YourForm']))
        {
            $model->attributes=$_POST['YourForm'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('create',array(
        'model'=>$model,
        ));
    }

On the above:

$this->redirect(array('view','id'=>$model->id));

automatically gives you the last ID inserted so you can just put the following in your view:

echo "Form:".$id;


标签: php yii