Help with ActiveForm updates via PAJAX

Hi All,

Need some help to figure out how things work between Yii ActiveForm, Pajax, and JS. In my current working implementation, I have an initial form with radio button for selecting the new customer type to create (e.g. business vs residential), and based on the selection, the proper form is then rendered in a separate page (after submit, no AJAX).

I’d like to change that to handle it all in one form w/o the need for submission. I created a separate form and controller function to call this ‘one page form’ which initially only has a dropdown menu for selection of business vs residential. Then, via PAJAX (I added JS code to the view), the client requests either form. The form is displayed but the client validations are lost. What do I need to do to so that client validations on the form loaded via PAJAX are executed?

This is the view for the single-page form:

<?php

use yii\helpers\Html;
use yii\widgets\Pjax;
// use yii\bootstrap\ActiveForm;
use yii\widgets\ActiveForm;


/* @var $this yii\web\View */
/* @var $model app\models\Cliente2 */

$this->title = Yii::t('app', 'Create Cliente2 with single page');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Cliente2s'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;

    Html::encode($this->title);
?>

    <div class="cliente-create-entireform">

<?php

    Pjax::begin([
        // Pjax options
    ]);
        $form = ActiveForm::begin([
            'id' => 'cliente-create-singlepage',
            'options' => ['data' => ['pjax' => true]],
            'enableAjaxValidation' => true,
            // 'enableClientValidation' => true,
            // more ActiveForm options
        ]);

        echo $form->field($model, 'tipoCliente')->dropDownList([
            'personafisica' => 'Persona Fisica',
            'personamoral' => 'Persona Moral'],
            ['prompt' => 'Seleccione tipo de Cliente']);

        ActiveForm::end();

    Pjax::end();

?>

</div>

<?php

  $this->registerJs(
        "$( '#cliente2-tipocliente' ).on('change', function() {

            const selected_text = $( this ).val();

            console.log('User selected ' + selected_text);

            

            $.ajax({

                url: 'index.php?r=cliente2/'+selected_text,

                type: 'GET',

                dataType: 'html',

            })
            
            .done(function( data ) {

                console.log( 'Sample of data:', data.slice( 0, 2000) );
                var myNewElement = $( data );
                myNewElement.appendTo('.cliente-create-entireform'); 

            })


            .fail(function( xhr, status, errorThrown ) {
                alert( 'Sorry, there was a problem!');
                console.log( 'Error: ' + errorThrown );
                console.log( 'Status: ' + status );
                console.dir( xhr );
            })

            

        })",
        $this::POS_READY,
        'cliente-form-pjax');

?>

Added the following functions to the controller…

public function actionCreatesinglepage() {

    $model = new Cliente2();

    $model->usuario = Yii::$app->user->id;

    $loaded = $model->load(Yii::$app->request->post());

    $loaded_str = 'no';

    if ($loaded) {
        $loaded_str = 'yes';
    }

    Yii::trace('Loaded model from post request: '.$loaded_str);

    if ($model->tipoCliente != 'Persona Fisica' && $model->tipoCliente != 'Persona Moral') {

        // first form for new record creation:
        return $this->render('createsinglepage', [
            'model' => $model
        ]);
    }
}

And… the function below is called via AJAX when the user selects ‘Persona Fisica’ in the dropdown:

public function actionPersonafisica() {

        if (Yii::$app->request->isAjax) {

            Yii::trace('actionPersonafisica():: request is Ajax');
        }

        $model = new Cliente2();

        $model->usuario = Yii::$app->user->id;

        $model->tipoCliente = 'Persona Fisica';

        $loaded = $model->load(Yii::$app->request->post());

        if (!$loaded) {

            Yii::trace('actionPersonafisica()::did NOT load model from request');

            return $this->render('_personaFisicaFormv2', ['model' => $model, 'msg' => 'Usuario selecciono persona fisica']);
        }

        // model loaded from request...
        // ajax validate
        if (Yii::$app->request->isAjax) {

            Yii::trace('actionPersonafisica():: request is Ajax');

            return \yii\widgets\ActiveForm::validate($model); 
        }

        $model->fechaNacimiento = Cliente2::formatDate($model->fechaNacimiento);

        if (!$model->exists()) {

                $saved = $model->save();

                if ($saved) {

                    Yii::trace('Saved new Cliente2 persona fisica record to DB');

                    return $this->redirect(['view', 'id' => $model->id]);
                }
                else {

                    Yii::trace('Record does not exist but could not save new Cliente2 record to DB!');

                    throw new Exception ('El nuevo record de cliente no existe en la base de datos pero no se pudo crear/guardar en la base de datos');
                }
        }

        else {    
        
            // Cliente2 already exists in DB

            Yii::trace('Cliente2 record already exists in DB, could not save it!');

            return $this->render ('createPersonaFisica', ['model' => $model, 'msg' => 'Cliente ya existe en base de datos! Verifica que nombre, apellidos, y fecha de nacimiento no sean identicos!']);  

        }
}

(* still need to create a similar function for Personamoral (business customer) but I expect to work the same way as the above *)

Thank you,

Mario.