PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 20, 2022

[FIXED] yii2 - dynamic activeform and client validation

 February 20, 2022     yii, yii2     No comments   

Issue

I am rendering an ActiveForm dynamically via ajax, however because the form isn't there on page load, the necessary JS files yiiActiveForm.js, yii.validation.js) and the associated validation triggers aren't there when the form is echoed out.

Here is some sample code:

JS:

$('.btn-edit').on('click', function() {
    var id = $(this).attr('data-id');
    var url = base_url + '/account/editreview/' + id;

    $.ajax({
        type: 'post',
        url: url,
        dataType: 'json',
        success: function(result) {
            $('.popup').html(result.html);
        }
    });
});

Controller:

public function actionEditReview($id)
{
    $return_array = [
        'html' => null,
    ];

    $review = $this->findReview($id);

    $return_array['html'] = $this->renderPartial('review-popup', [
        'review' => $review,
    ]);

    echo json_encode($return_array);
}

View (review-popup.php):

<?php
use yii\widgets\ActiveForm;
?>

<?php $form = ActiveForm::begin([
    'id' => 'review-form',
    'enableAjaxValidation' => false,
    'enableClientValidation' => true,
]); ?>

<?php echo $form->field($review, 'title')->textInput(); ?>

<button type="submit" class="btn-edit" data-id="<?php echo $review->id; ?>">Submit</button>

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

I have read the notes on this page https://yii2-cookbook.readthedocs.io/forms-activeform-js/ but this talks about adding validation to single attributes, and not to an entire form.

Does anyone know how to do this?


Solution

I found the solution: use renderAjax() instead of renderPartial() when echoing out the view.

http://www.yiiframework.com/doc-2.0/yii-web-view.html#renderAjax()-detail



Answered By - MAX POWER
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing