在更改Yii2时启用activeForm验证

时间:2017-07-13 08:32:16

标签: php validation yii2

我正在尝试启用像'validateOnChange' => true这样的更改验证过程,但没有结果。当我在它外面点击时也试图验证输入,但它只发生在部分表格上,例如在登录表单中它是好的但在我的自定义表单中它不起作用。 有我的表单代码:

<?php $form = ActiveForm::begin([
                                'enableAjaxValidation' => true,
                                'enableClientValidation' => false,
                                'validateOnBlur' => false,
                                'validateOnType' => false,
                                'validateOnChange' => true,
                                'options' => ['enctype' => 'multipart/form-data']]); ?>

                            <?= $form->field($modelRequest, 'phone')->textInput(['maxLength' => true, 'class' => 'product-request-input', 'placeholder' => 'телефон'])->label(false) ?>

                            <?= $form->field($modelRequest, 'email')->textInput(['maxlength' => true, 'class' => 'product-request-input', 'placeholder' => 'email'])->label(false) ?>


                            <?= $form->field($modelRequest, 'subject')->activeTextInput(['maxLength' => true, 'class' => 'product-request-input', 'placeholder' => 'тема'])->label(false) ?>

                            <?= $form->field($modelRequest, 'question')->textarea(['rows' => 4, 'class' => 'product-request-input', 'placeholder' => 'съобщение'])->label(false) ?>

                              <?= Html::activeHiddenInput($modelRequest, 'product_id', ['value' => $product->id]) ?>

                            <?= '<img src="' . $_SESSION['captcha']['image_src'] . '" alt="CAPTCHA code" height="60" width="120" style="display: block; float: left;">' ?>

                            <?= $form->field($modelRequest, 'captcha_code')->textInput(['maxlength' => true, 'class' => 'captcha-request-input', 'maxlength' => 5])->label(false) ?>

                            <?= Html::submitButton(Yii::t('app', 'app.send'), ['class' => 'request-send-btn']) ?>

                            <?= Html::resetButton(Yii::t('app', 'app.clear'), ['class' => 'request-send-btn']) ?>

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

我的模特规则:

public function rules()
    {
        return [
            [[/*'name', */'subject', 'email', /*'phone', */'question'], 'required'],
            ['email', 'email'],
            [['phone', 'product_id','status'], 'integer'],
            [['question'], 'string'],
            [['dt'], 'safe'],
            [['name', 'subject'], 'string', 'max' => 255],
            [['email'], 'string', 'max' => 100],
            [['product_id'], 'exist', 'skipOnError' => true, 'targetClass' => Product::className(), 'targetAttribute' => ['product_id' => 'id']],
        ];
    }

好像我错过了这个过程中的一些东西。 提前谢谢!

编辑:控制器操作:

public function actionProduct() {
        $first_step = Yii::$app->getRequest()->getQueryParam('first_step');
        $second_step = Yii::$app->getRequest()->getQueryParam('second_step');
        $product_step = Yii::$app->getRequest()->getQueryParam('product');
        $last = explode('-', $first_step);
        $id = end($last);
        $cat = Page::findOne($id);
        $lang = \frontend\models\Lang::getCurrent();
        $lisingChoice = new LisingChoice;
        $messageBro = '';
        $flagCaptcha = 0;
        $flagSend = 0;

        if (isset($cat) and $cat->url == $first_step) {
            $last = explode('-', $second_step);
            $id = end($last);
            $subcat = Page::findOne($id);
            $product = Product::findOne($id);
            $similar = Product::find()->joinWith('cats')->where('product_cat.product_id != :current_prod AND product_cat.page_id = :page1 AND product.quantity > 0', [':current_prod' => $product->id, ':page1' => $cat->id])->groupBy(['id'])->orderBy(new Expression('rand()'))->limit(12)->all();

            $allratings = ProductReview::find()->where('active=1 and product_id='.$id)->all();
            $relatedProducts = ProductRelated::find()->joinWith('relProduct')->where('product_related.main_product_id = :id AND product.active = 1', ['id' => $product->id])->orderBy('product.id')->all();
            if (Yii::$app->system->getGalleryTypeName() == 'fotorama') {
                Yii::$app->view->registerJsFile('/js/fotorama.js', ['position' => \yii\web\View::POS_END]);
                Yii::$app->view->registerCssFile("/css/fotorama.css", [
                    'depends' => [BootstrapAsset::className()],
                        ], 'css-theme');
            }
            if (isset($subcat) and $subcat->url == $second_step) {
                $last = explode('-', $product_step);
                $id = end($last);
                $product = Product::findOne($id);

                if ($product and $product->url == $product_step) {
                    Yii::$app->view->registerMetaTag([
                        'name' => 'description',
                        'content' => strip_tags(Yii::$app->OutData->showTXT($product->meta_description)),
                    ]);
                    Yii::$app->view->registerMetaTag([
                        'property' => 'og:image',
                        'content' => "http://" . $_SERVER['SERVER_NAME'] . $product->getImgWithoutKey(),
                    ]);

                    //$related = ProductRelated::find()->joinWith('relProduct')->where('product_related.main_product_id = :id AND product.active = 1', ['id' => $product->id])->orderBy(new Expression('rand()'))->limit(4)->all();
                    $related = Product::find()->joinWith('cats')->where('product_cat.product_id != :current_prod AND (product_cat.page_id = :page1 OR product_cat.page_id = :page2) AND product.quantity > 0 AND product.edit_mw = 1', [':current_prod' => $product->id, ':page1' => $cat->id, ':page2' => $subcat->id])->groupBy(['id'])->orderBy(new Expression('rand()'))->limit(5)->all();
                    $prodReviews = ProductReview::find()->where('active = 1 AND product_id =' . $product->id);
                    $dataProviderReviews = new ActiveDataProvider([
                        'query' => $prodReviews,
                        'pagination' => [
                            'pageSize' => 10,
                            'route' => Yii::$app->makeUrl->makeProductUrl($product->id),
                        ],
                        'sort' => [
                            'defaultOrder' => [
                                'dt' => SORT_DESC,
                            ]
                        ],
                    ]);
                    return $this->render('product', [
                                'product' => $product,
                                'subcat' => $subcat,
                                'cat' => $cat,
                                'allratings' => $allratings,
                                'similar' => $similar,
                                'related' => $related,
                                'dataProviderReviews' => $dataProviderReviews,
                                'lisingChoice' => $lisingChoice,
                                  'messageBro' => $messageBro,
                    ]);
                } else {
                    if (YII_DEBUG) {
                        $message = '#3<br>Controller: <strong>' . Yii::$app->controller->id . '</strong><br>Action: <strong>' . Yii::$app->controller->action->id . '</strong>';
                        return $this->render('error', [ 'message' => $message]);
                    } else {
                        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
                    }
                }
            } elseif (isset($product) and $product->url == $second_step) {

                Yii::$app->view->registerMetaTag([
                    'name' => 'description',
                    'content' => strip_tags(Yii::$app->OutData->showTXT($product->meta_description)),
                ]);
                Yii::$app->view->registerMetaTag([
                    'property' => 'og:image',
                    'content' => "http://" . $_SERVER['SERVER_NAME'] . $product->getImgWithoutKey(),
                ]);
                $related = Product::find()->joinWith('cats')->joinWith('cats.page')->where('product_cat.product_id != :current_prod AND (product_cat.page_id = :page1 OR page.id_in = :page2)  AND product.quantity > 0 AND product.edit_mw = 1', [':current_prod' => $product->id, ':page1' => $cat->id, ':page2' => $cat->id])->groupBy(['id'])->orderBy(new Expression('rand()'))->limit(5)->all();
                $prodReviews = ProductReview::find()->where('active = 1 AND product_id =' . $product->id);
                $dataProviderReviews = new ActiveDataProvider([
                    'query' => $prodReviews,
                    'pagination' => [
                        'pageSize' => 10,
                        'route' => Yii::$app->makeUrl->makeProductUrl($product->id),
                    ],
                    'sort' => [
                        'defaultOrder' => [
                            'dt' => SORT_DESC,
                        ]
                    ],
                ]);

                $modelRequest = new RequestProduct();

                if ($modelRequest->load(Yii::$app->request->post()) ) {

                    if ($_SESSION['captcha']['code'] != $_POST['RequestProduct']['captcha_code']) {
                        $flagCaptcha = 1;
                    } else {
                        if ( $modelRequest->save() ) {
                                $flagSend = 1;
                                /*$modelRequest->name = $_POST['RequestProduct']['name'];*/
                                if(isset($_POST['RequestProduct']['phone']) && !empty($_POST['RequestProduct']['phone']))
                                {
                                    $modelRequest->phone = $_POST['RequestProduct']['phone'];
                                }
                                $modelRequest->email = $_POST['RequestProduct']['email'];
                                $modelRequest->question = $_POST['RequestProduct']['question'];
                                $modelRequest->subject = $_POST['RequestProduct']['subject'];
                                $modelRequest->product_id = $id;
                                $modelRequest->save(false);
                         }else{
                                $flagSend = 2;
                            }
                        }
                    }


                return $this->render('product', [
                            'product' => $product,
                            'subcat' => $subcat,
                            'cat' => $cat,
                            'related' => $related,
                            'dataProviderReviews' => $dataProviderReviews,
                            'lisingChoice' => $lisingChoice,
                            'flagCaptcha' => $flagCaptcha,
                            'modelRequest' => $modelRequest,
                            'relatedProducts' => $relatedProducts,
                            'similar' => $similar,
                            'allratings' => $allratings,
                            'flagSend' => $flagSend,
                ]);
            } else {
                if (YII_DEBUG) {
                    $message = '#2<br>Controller: <strong>' . Yii::$app->controller->id . '</strong><br>Action: <strong>' . Yii::$app->controller->action->id . '</strong>';
                    return $this->render('error', [ 'message' => $message]);
                } else {
                    throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
                }
            }
        } else {
            if (YII_DEBUG) {
                $message = '#1<br>Controller: <strong>' . Yii::$app->controller->id . '</strong><br>Action: <strong>' . Yii::$app->controller->action->id . '</strong>';
                return $this->render('error', [ 'message' => $message]);
            } else {
                throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
            }
        }
    }

0 个答案:

没有答案