C
C
CodeBuilder2015-07-28 22:42:08
JavaScript
CodeBuilder, 2015-07-28 22:42:08

Yii2 does not return errors when validating a modal window, although there are some why?

I've been learning the framework for a week.
I'm trying to organize authorization in a modal window . I d6143dc14ac242b2b40f1710af4cfc16.jpg
used several methods:
1) renderAjax - there is some success here, because the data is validated, the form is delayed if the data is correct - authorization occurs with the appropriate redirect, but I can't catch validation errors, they just are not output.
//======Action====//

public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }	
    $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
        	
             $success=true;
                return $this->redirect(['models/girls']);
        } else {
        	
            return $this->renderAjax('getForm', [
                'model' => $model,
            ]);
        }
    }

//=====view=====//
$this->title = 'Login';
$this->params['breadcrumbs'][] = $this->title;
?>
          


      <div = id="signin-title-cont">
        <span id="signin-head"><i class="fa fa-sign-in"></i>&nbsp;sign&nbsp;in</span>
        <span class="signin-close">x</span>
      </div>
      
      
      
        <?php $form = ActiveForm::begin([
        'id' => 'login-form',
        'options' => ['class' => 'signin-form'],
      'enableAjaxValidation' => true,
    	//	'validateOnChange' => true,
    	//	'validateOnSubmit' => true,
        
        'fieldConfig' =>[
    		'template' => "{label}\n{input}\n{error}",    		
    	]]
        ); ?>
        
        
        
        
      <?php Yii::$app->view->registerJsFile( //Сдесь регистрирую js файл который должен задерживать сабмит формы и ловить ответ
    'lag/frontend/web/assets/login.js',['depends' => 'yii\web\YiiAsset' ]); ?> <!--js файл регистрируеться тту все норм-->
          
          
          
          
                <?= $form->field($model, 'login') ?>
              	 
                <?= $form->field($model, 'password')->passwordInput() ?>
             
               
                <div class="form-group">
                    <?= Html::submitButton('Login', ['class' => 'signinbutton', 'name' => 'login-button']) ?>
                </div>
            <?php ActiveForm::end(); ?>


//=========js==========//
//alert('hi');
$('#login-form').submit(function (e) {     
     return false;
        var form = $(this);
        $.ajax({
            url: "index.php?r=/site/login",
            type: "POST",
            data: form.serialize(),
    //	contentType: "application/json; charset=utf-8",
      //dataType: "json",
            success: function (result) {
                console.log(result);
                if (result == 'true') {
                    alert('true');//$('#my-modal').modal('hide');
                }
                else {
                  //  var modalContainer = $('.signin-wrap');
                    var modalBody = $('.signin-wrap');
                    modalBody.html(result);
                }
            }
        });
    });


2)renderPartial - it's not possible to render the form into a modal window, it just redirects to the action, although validation occurs, and returns errors.
public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        
      
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
        	
             $success=true;
                return $this->redirect(['models/girls']);
        } else {
        	
            return $this->renderPartial('getForm', [
                'model' => $model,
            ]);
        }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
CodeBuilder, 2015-07-29
@CodeBuilder

After several attempts, we decided to bypass Yii2_ajaxValidation with our code, found some success, the data is validated, the form does not leave, with valid data, the login is performed, but there are doubts about the reliability and security of my method, see:
And so I send the data in the forehead in the action:
/ ///===============Action===================////

public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        
     
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post())) {
        	 if($model->login()){
        	 	return $this->redirect(['models/girls']);
        	 }
       else{
       	echo 2;     //////=========Если ошибка, кидаю двойку в аякс
       }       
        } else {
            return $this->renderAjax('getForm', [
                'model' => $model,
            ]);
        }

  }

I accept the error myself and process it, using js-code in view, that is, if I receive an error, then I display messages on my own without the participation of Yii and color the inputs:
////================ ================View================================ ======////
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\bootstrap\Modal;

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\LoginForm */
 /*<!--<?= $form->field($users, 'rememberMe')->checkbox() ?>-->*/

$this->title = 'Login';
$this->params['breadcrumbs'][] = $this->title;
?>

      <div = id="signin-title-cont">
        <span id="signin-head"><i class="fa fa-sign-in"></i>&nbsp;sign&nbsp;in</span>
        <span class="signin-close">x</span>
      </div>
      <?php $form = ActiveForm::begin([
            'id' => 'login-form',
            'options' => ['class' => 'signin-form'],
          	  'enableAjaxValidation' => true,
        	//	  'validateOnChange' => true,
        	//	  'validateOnSubmit' => true,
            
            'fieldConfig' =>[
        		'template' => "{label}\n{input}\n{error}",    		
        	]]
            ); 
      ?>
          
      <!--<?php Yii::$app->view->registerJsFile( //Сдесь регистрирую js файл который должен задерживать сабмит формы и ловить ответ
    'lag/frontend/web/assets/login.js',['depends' => 'yii\web\YiiAsset' ]); ?> <!--js файл регистрируеться тту все норм-->
        
        <?= $form->field($model, 'login') ?>
              	 
                <?= $form->field($model, 'password')->passwordInput() ?>
             
               
                <div class="form-group">
                    <?= Html::submitButton('Login', ['class' => 'signinbutton', 'name' => 'login-button']) ?>
                </div>
<?php ActiveForm::end(); ?>
<?php
///////==================================================code JS to PERFOM ERRORS FROM ACTION/LOGIN========================================================================/////// 
$script = <<< JS
$('form#login-form').on('beforeSubmit', function(e)
{
  var form = $(this);
  $.post(
    form.attr('action'),
    form.serialize()
  )
  .done(function(result){
    if(result == 2){
      $('.field-loginform-password').addClass('has-error');
      $('.field-loginform-password').append('<p class="help-block help-block-error">Incorrect username or password.</p>');
      $('.field-loginform-login').addClass('has-error');
    }
  });
  
  return false;
});

function signinHide(){
  $('.signin').css({'background' : '#fff',
          'color' : 'rgba(0,0,0, 0.4)'});
  
  $('.signin-container')
  .find('.signin-wrap')
  .animate({
  marginLeft : '-1000px'}, 500, 
    function(){
      $('.signin-container').css({'display' : 'none'});
    });
  }

  $('.signin-close').bind("click", signinHide);
JS;
$this->registerJs($script);

K
kompi, 2015-07-29
@kompi

See the yii.active-form.js sources for how it handles errors from the server.
PS It's better not to use custom ajax requests if you use ActiveForm ajax validation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question