dongsheng4126335 2017-10-22 06:39
浏览 73
已采纳

表格未在yii2中提交

I'm using yii2 advanced app and im stuck at a point where my form doesn't get submitted. It refreshes and stays on the same page. There are no errors shown too.

Here is the model code Countries.php

<?php

namespace backend\models\base;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\BlameableBehavior;
use mootensai\behaviors\UUIDBehavior;

/**
 * This is the base model class for table "countries".
 *
 * @property integer $id
 * @property string $sortname
 * @property string $name
 * @property integer $phonecode
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $created_by
 * @property integer $updated_by
 * @property integer $deleted_at
 * @property integer $deleted_by
 *
 * @property \backend\models\States[] $states
 */
class Countries extends \yii\db\ActiveRecord
{
    use \mootensaielation\RelationTrait;

    private $_rt_softdelete;
    private $_rt_softrestore;

    public function __construct(){
        parent::__construct();
        $this->_rt_softdelete = [
            'deleted_by' => \Yii::$app->user->id,
            'deleted_at' => date('Y-m-d H:i:s'),
        ];
        $this->_rt_softrestore = [
            'deleted_by' => 0,
            'deleted_at' => date('Y-m-d H:i:s'),
        ];
    }

    /**
    * This function helps \mootensaielation\RelationTrait runs faster
    * @return array relation names of this model
    */
    public function relationNames()
    {
        return [
            'states'
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['sortname', 'name', 'phonecode'], 'required'],
            [['phonecode', 'created_at', 'updated_at', 'created_by', 'updated_by', 'deleted_at', 'deleted_by'], 'integer'],
            [['sortname'], 'string', 'max' => 3],
            [['name'], 'string', 'max' => 150],
            [['lock'], 'default', 'value' => '0'],
            [['lock'], 'mootensai\components\OptimisticLockValidator']
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'countries';
    }

    /**
     *
     * @return string
     * overwrite function optimisticLock
     * return string name of field are used to stored optimistic lock
     *
     */
    public function optimisticLock() {
        return 'lock';
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'sortname' => Yii::t('app', 'Sortname'),
            'name' => Yii::t('app', 'Name'),
            'phonecode' => Yii::t('app', 'Phonecode'),
        ];
    }



    /**
     * @return \yii\db\ActiveQuery
     */
    public function getStates()
    {
        return $this->hasMany(\backend\models\States::className(), ['country_id' => 'id']);
    }

    /**
     * @inheritdoc
     * @return array mixed
     */
    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'updated_at',
                'value' => new \yii\db\Expression('NOW()'),
            ],
            'blameable' => [
                'class' => BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',
            ],
            'uuid' => [
                'class' => UUIDBehavior::className(),
                'column' => 'id',
            ],
        ];
    }


    /**
     * @inheritdoc
     * @return \backend\models\query\CountriesQuery the active query used by this AR class.
     */
    public static function find()
    {
        $query = new \backend\models\query\CountriesQuery(get_called_class());
        return $query->where(['countries.deleted_by' => 0]);
    }
}

And the controller CountriesController.php

<?php

namespace backend\controllers;

use Yii;
use backend\models\Countries;
use backend\models\search\CountriesSearch;
use backend\controllers\BackendController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;


/**
 * CountriesController implements the CRUD actions for Countries model.
 */
class CountriesController extends BackendController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index', 'view', 'create', 'update', 'delete', 'pdf', 'save-as-new','add-states'],
                        'roles' => ['admin']
                    ],
                    [
                        'allow' => false
                    ]
                ]
            ]
        ];
    }

    /**
     * Lists all Countries models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CountriesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Countries model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);

        $providerStates = new \yii\data\ArrayDataProvider([
            'allModels' => $model->states,
        ]);
        return $this->render('view', [
            'model' => $this->findModel($id),
            'providerStates' => $providerStates,
        ]);
    }

    /**
     * Creates a new Countries model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Countries();

        if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Countries model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        if (Yii::$app->request->post('_asnew') == '1') {
            $model = new Countries();
        }else{
            $model = $this->findModel($id);
        }

        if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Countries model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->deleteWithRelated();

        return $this->redirect(['index']);
    }

    /**
     * 
     * Export Countries information into PDF format.
     * @param integer $id
     * @return mixed
     */
    public function actionPdf($id) {
        $model = $this->findModel($id);
        $providerStates = new \yii\data\ArrayDataProvider([
            'allModels' => $model->states,
        ]);

        $content = $this->renderAjax('_pdf', [
            'model' => $model,
            'providerStates' => $providerStates,
        ]);

        $pdf = new \kartik\mpdf\Pdf([
            'mode' => \kartik\mpdf\Pdf::MODE_CORE,
            'format' => \kartik\mpdf\Pdf::FORMAT_A4,
            'orientation' => \kartik\mpdf\Pdf::ORIENT_PORTRAIT,
            'destination' => \kartik\mpdf\Pdf::DEST_BROWSER,
            'content' => $content,
            'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
            'cssInline' => '.kv-heading-1{font-size:18px}',
            'options' => ['title' => \Yii::$app->name],
            'methods' => [
                'SetHeader' => [\Yii::$app->name],
                'SetFooter' => ['{PAGENO}'],
            ]
        ]);

        return $pdf->render();
    }

    /**
    * Creates a new Countries model by another data,
    * so user don't need to input all field from scratch.
    * If creation is successful, the browser will be redirected to the 'view' page.
    *
    * @param mixed $id
    * @return mixed
    */
    public function actionSaveAsNew($id) {
        $model = new Countries();

        if (Yii::$app->request->post('_asnew') != '1') {
            $model = $this->findModel($id);
        }

        if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('saveAsNew', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Finds the Countries model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Countries the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Countries::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
        }
    }



    /**
    * Action to load a tabular form grid
    * for States
    * @author Yohanes Candrajaya <moo.tensai@gmail.com>
    * @author Jiwantoro Ndaru <jiwanndaru@gmail.com>
    *
    * @return mixed
    */
    public function actionAddStates()
    {
        if (Yii::$app->request->isAjax) {
            $row = Yii::$app->request->post('States');
            if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
                $row[] = [];
            return $this->renderAjax('_formStates', ['row' => $row]);
        } else {
            throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
        }
    }
}

and the view file create.php

<?php

use yii\helpers\Html;


/* @var $this yii\web\View */
/* @var $model backend\models\Apps */

$this->title = Yii::t('app', 'Create Apps');
?>
<div class="uk-container uk-container-small uk-position-relative">
    <div><!----> <div>
    <h1 id="navbar" class="uk-h2 tm-heading-fragment">
        <a href="#navbar">Apps</a>
    </h1>

    <!-- Start Breadcrumb -->
    <ul class="uk-breadcrumb">
        <li><?= Html::a('Admin', ['/'])?></li>
        <li><?= Html::a('Apps', ['/apps'])?></li>
        <li>Create</li>
    </ul>
    <!-- End Breadcrumb -->

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>

</div>

and view _form.php

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use alexeevdv\widget\SluggableInputWidget;
use dosamigos\ckeditor\CKEditor;

/* @var $this yii\web\View */
/* @var $model backend\models\Apps */
/* @var $form yii\widgets\ActiveForm */

?>

<div class="uk-margin-auto">

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->errorSummary($model); ?>


    <?= $form->field($model, 'title')->textInput(['maxlength' => true, 'placeholder' => 'Title']) ?>

    <?= $form->field($model, 'slug')->widget(SluggableInputWidget::className(), [
        'dependsOn' => 'title',    
    ]); ?>

    <?= $form->field($model, 'content')->widget(CKEditor::className(), [
        'options' => ['rows' => 6],
        'preset' => 'basic',
        'clientOptions' => [
            'filebrowserImageBrowseUrl' => yii\helpers\Url::to(['imagemanager/manager', 'view-mode'=>'iframe', 'select-type'=>'ckeditor']),
        ]
    ]);?>

    <?= $form->field($model, 'video')->textInput(['maxlength' => true, 'placeholder' => 'Video']) ?>

    <?= $form->field($model, 'category')->widget(\kartik\widgets\Select2::classname(), [
        'data' => \yii\helpers\ArrayHelper::map(\backend\models\Categories::find()->orderBy('id')->asArray()->all(), 'id', 'name'),
        'options' => ['placeholder' => Yii::t('app', 'Choose a category')],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]); ?>

    <?= $form->field($model, 'status')->textInput(['placeholder' => 'Status']) ?>

    <div class="form-group">
    <?php if(Yii::$app->controller->action->id != 'save-as-new'): ?>
        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn uk-button uk-button-primary' : 'btn uk-button uk-button-primary']) ?>
    <?php endif; ?>
    <?php if(Yii::$app->controller->action->id != 'create'): ?>
        <?= Html::submitButton(Yii::t('app', 'Save As New'), ['class' => 'btn uk-button uk-button-default', 'value' => '1', 'name' => '_asnew']) ?>
    <?php endif; ?>
        <?= Html::a(Yii::t('app', 'Cancel'), Yii::$app->request->referrer , ['class'=> 'btn uk-button uk-button-danger']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

I've browsed few articles, but of no help. My form has a <?php ActiveForm::end(); ?> at the end of the form. I also tried to remove the select2 widget but i still get the same issue. Could someone help me out why this is happening?

Html output rendered of create.php

<div class="uk-container uk-container-small uk-position-relative">
    <div><!----> <div>
    <h1 id="navbar" class="uk-h2 tm-heading-fragment">
        <a href="#navbar">Countries</a>
    </h1>

    <!-- Start Breadcrumb -->
    <ul class="uk-breadcrumb">
        <li><a href="/final/backend/en-us">Admin</a></li>
        <li><a href="/final/backend/en-us/countries">Countries</a></li>
        <li>Create</li>
    </ul>
    <!-- End Breadcrumb -->


<div class="uk-margin-auto">

    <form id="w0" action="/final/backend/en-us/countries/create" method="post">
<input type="hidden" name="_csrf" value="zIvM0awWY3XpcrF1kY6gFY00ghnL1cgwTYhaEqF7RO2hch4x5AznMwtfWxWp4D-YW9yJy5aiNupb0JnMSbi5qQ==">
    <div class="error-summary" style="display:none"><p>Please fix the following errors:</p><ul></ul></div>
    <div class="form-group field-countries-id">
<input type="text" id="countries-id" class="form-control" name="Countries[id]" style="display:none">
</div>
    <div class="form-group field-countries-sortname required">
<label class="control-label" for="countries-sortname">Sortname</label>
<input type="text" id="countries-sortname" class="form-control" name="Countries[sortname]" maxlength="3" placeholder="Sortname" aria-required="true">

<div class="help-block"></div>
</div>
    <div class="form-group field-countries-name required">
<label class="control-label" for="countries-name">Name</label>
<input type="text" id="countries-name" class="form-control" name="Countries[name]" maxlength="150" placeholder="Name" aria-required="true">

<div class="help-block"></div>
</div>
    <div class="form-group field-countries-phonecode required">
<label class="control-label" for="countries-phonecode">Phonecode</label>
<input type="text" id="countries-phonecode" class="form-control" name="Countries[phonecode]" placeholder="Phonecode" aria-required="true">

<div class="help-block"></div>
</div>
    <div id="w3-container" class=" tabs-above tab-align-left tabs-krajee"><ul id="w3" class="nav nav-tabs nav nav-tabs hidden-print" data-krajee-tabsx="tabsX_0b4b2adf" role="tablist"><li class="active"><a href="#w3-tab0" data-toggle="tab" role="tab"><i class="glyphicon glyphicon-book"></i> States</a></li></ul>
<div class="tab-content printable"><div class="h3 visible-print-block"><i class="glyphicon glyphicon-book"></i> States</div>
<div id="w3-tab0" class="tab-pane fade in active"><div class="form-group" id="add-states">
<div id="w1" class="grid-view hide-resize" data-krajee-grid="kvGridInit_7fee31f2"><div class="panel panel-default">


    <div class="rc-handle-container" style="width: 628px;"><div class="rc-handle" style="left: 50px; height: 37px;"></div><div class="rc-handle" style="left: 496px; height: 37px;"></div></div><div id="w1-container" class="table-responsive kv-grid-container"><table class="kv-grid-table table table-hover kv-table-wrap"><thead>

<tr><th class="kv-align-center kv-align-middle" style="width: 7.96%;" data-col-seq="0">#</th><th class="kv-align-top kv-grid-hide" data-col-seq="1">Id</th><th class="kv-align-top" data-col-seq="2" style="width: 71.02%;">Name</th><th class="kv-align-middle" data-col-seq="3" style="width: 21.02%;"></th></tr>

</thead>
<tbody>
<tr><td colspan="4"><div class="empty">No results found.</div></td></tr>
</tbody></table></div>
    <div class="kv-panel-after"><button type="button" class="btn btn-success kv-batch-create" onclick="addRowStates()"><i class="fa fa-plus"></i>Add States</button></div>

</div></div>    </div>


</div>
</div></div>    <div class="form-group">
            <button type="submit" class="uk-button uk-button-primary">Create</button>                <a class="uk-button uk-button-danger">Cancel</a>    </div>

    </form>
</div>

</div>
            </div>
        </div>
  • 写回答

1条回答 默认 最新

  • doulangchao8934 2017-10-22 09:35
    关注

    Changing loadAll() and saveAll() to load() and save() has solved the issue

    <?php
    
    namespace backend\controllers;
    
    use Yii;
    use backend\models\Countries;
    use backend\models\search\CountriesSearch;
    use backend\controllers\BackendController;
    use yii\web\NotFoundHttpException;
    use yii\filters\VerbFilter;
    
    /**
     * CountriesController implements the CRUD actions for Countries model.
     */
    class CountriesController extends BackendController
    {
        public function behaviors()
        {
            return [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'delete' => ['post'],
                    ],
                ],
                'access' => [
                    'class' => \yii\filters\AccessControl::className(),
                    'rules' => [
                        [
                            'allow' => true,
                            'actions' => ['index', 'view', 'create', 'update', 'delete', 'pdf', 'save-as-new','add-states'],
                            'roles' => ['admin']
                        ],
                        [
                            'allow' => false
                        ]
                    ]
                ]
            ];
        }
    
        /**
         * Lists all Countries models.
         * @return mixed
         */
        public function actionIndex()
        {
            $searchModel = new CountriesSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    
            return $this->render('index', [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
            ]);
        }
    
        /**
         * Displays a single Countries model.
         * @param integer $id
         * @return mixed
         */
        public function actionView($id)
        {
            $model = $this->findModel($id);
    
            $providerStates = new \yii\data\ArrayDataProvider([
                'allModels' => $model->states,
            ]);
            return $this->render('view', [
                'model' => $this->findModel($id),
                'providerStates' => $providerStates,
            ]);
        }
    
        /**
         * Creates a new Countries model.
         * If creation is successful, the browser will be redirected to the 'view' page.
         * @return mixed
         */
        public function actionCreate()
        {
            $model = new Countries();
    
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            } else {
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
        }
    
        /**
         * Updates an existing Countries model.
         * If update is successful, the browser will be redirected to the 'view' page.
         * @param integer $id
         * @return mixed
         */
        public function actionUpdate($id)
        {
            if (Yii::$app->request->post('_asnew') == '1') {
                $model = new Countries();
            }else{
                $model = $this->findModel($id);
            }
    
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }
    
        /**
         * Deletes an existing Countries model.
         * If deletion is successful, the browser will be redirected to the 'index' page.
         * @param integer $id
         * @return mixed
         */
        public function actionDelete($id)
        {
            $this->findModel($id)->deleteWithRelated();
    
            return $this->redirect(['index']);
        }
    
        /**
         * 
         * Export Countries information into PDF format.
         * @param integer $id
         * @return mixed
         */
        public function actionPdf($id) {
            $model = $this->findModel($id);
            $providerStates = new \yii\data\ArrayDataProvider([
                'allModels' => $model->states,
            ]);
    
            $content = $this->renderAjax('_pdf', [
                'model' => $model,
                'providerStates' => $providerStates,
            ]);
    
            $pdf = new \kartik\mpdf\Pdf([
                'mode' => \kartik\mpdf\Pdf::MODE_CORE,
                'format' => \kartik\mpdf\Pdf::FORMAT_A4,
                'orientation' => \kartik\mpdf\Pdf::ORIENT_PORTRAIT,
                'destination' => \kartik\mpdf\Pdf::DEST_BROWSER,
                'content' => $content,
                'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
                'cssInline' => '.kv-heading-1{font-size:18px}',
                'options' => ['title' => \Yii::$app->name],
                'methods' => [
                    'SetHeader' => [\Yii::$app->name],
                    'SetFooter' => ['{PAGENO}'],
                ]
            ]);
    
            return $pdf->render();
        }
    
        /**
        * Creates a new Countries model by another data,
        * so user don't need to input all field from scratch.
        * If creation is successful, the browser will be redirected to the 'view' page.
        *
        * @param mixed $id
        * @return mixed
        */
        public function actionSaveAsNew($id) {
            $model = new Countries();
    
            if (Yii::$app->request->post('_asnew') != '1') {
                $model = $this->findModel($id);
            }
    
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            } else {
                return $this->render('saveAsNew', [
                    'model' => $model,
                ]);
            }
        }
    
        /**
         * Finds the Countries model based on its primary key value.
         * If the model is not found, a 404 HTTP exception will be thrown.
         * @param integer $id
         * @return Countries the loaded model
         * @throws NotFoundHttpException if the model cannot be found
         */
        protected function findModel($id)
        {
            if (($model = Countries::findOne($id)) !== null) {
                return $model;
            } else {
                throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
            }
        }
    
    
    
        /**
        * Action to load a tabular form grid
        * for States
        * @author Yohanes Candrajaya <moo.tensai@gmail.com>
        * @author Jiwantoro Ndaru <jiwanndaru@gmail.com>
        *
        * @return mixed
        */
        public function actionAddStates()
        {
            if (Yii::$app->request->isAjax) {
                $row = Yii::$app->request->post('States');
                if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
                    $row[] = [];
                return $this->renderAjax('_formStates', ['row' => $row]);
            } else {
                throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
            }
        }
    }
    

    Thank you @aendeerei for the quick help!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 如何提取csv文件中需要的列,将其整合为一篇完整文档,并进行jieba分词(语言-python)
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置