wbraganca / yii2-dynamicform

It is widget to yii2 framework to clone form elements in a nested manner, maintaining accessibility.
Other
436 stars 438 forks source link

Validating additional fields #9

Closed loter closed 9 years ago

loter commented 9 years ago

Hello,

Very good extension! I've implemented dynamicform in my project, but looks like it doesn't validate the additional fields created (for example if I click on [+] then try to submit form, only the initial form validates.)

Please advice! Thank you!

wbraganca commented 9 years ago

Ensure you have added all the fields you want to validate the 'FormFields' attribute. How is the code in your view?

loter commented 9 years ago

Hello,

I have this:

<?php DynamicFormWidget::begin([
                'dynamicItems' => '#form-qualifications',
                'dynamicItem' => '.form-qualifications-item',
                'model' => $modelsQualifications[0],
                'formId' => 'dynamic-form',
                'formFields' => [
                    'employee_qualification_position',
                    'employee_qualification_start_date',
                    'employee_qualification_end_date',
                    'employee_qualification_reason',
                    'employee_qualification_organisation',
                    'employee_qualification_town',
                    'employee_qualification_country',
                ],
                'options' => [
                    'limit' => 4, // the maximum times, an element can be cloned (default 999)
                ]
            ]); ?>
<div id="form-qualifications">
            <?php foreach ($modelsQualifications as $i => $modelQualifications): ?>
                <div class="form-qualifications-item panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title pull-left">Qualifications</h3>
                        <div class="pull-right">
                            <button type="button" class="clone btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
                            <button type="button" class="delete btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
                        </div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="panel-body">
                        <?php
                            // necessary for update action.
                            if (!$modelQualifications->isNewRecord) {
                                echo Html::activeHiddenInput($modelQualifications, "[{$i}]id");
                            }
                        ?>
                        <?= $form->field($modelQualifications, "[{$i}]employee_qualification_position")->textInput(['maxlength' => 64]) ?>
                        <div class="row">
                            <div class="col-sm-6">
                                <? // $form->field($modelQualifications, "[{$i}]employee_qualification_start_date")->textInput(['maxlength' => 128]) ?>
                                <?= yii\jui\DatePicker::widget(['name' => '[{'.$i.'}]employee_qualification_start_date', 'clientOptions' => ['defaultDate' => '2014-01-01']]) ?>
                            </div>
                            <div class="col-sm-6">
                                <?= $form->field($modelQualifications, "[{$i}]employee_qualification_end_date")->textInput(['maxlength' => 128]) ?>
                            </div>
                        </div><!-- .row -->
                        <div class="row">
                            <div class="col-sm-4">
                                <?= $form->field($modelQualifications, "[{$i}]employee_qualification_reason")->textInput(['maxlength' => 64]) ?>
                            </div>
                            <div class="col-sm-4">
                                <? //$form->field($modelQualifications, "[{$i}]employee_qualification_organisation")->textInput(['maxlength' => 32]) ?>
                            </div>
                            <div class="col-sm-4">
                                <?= $form->field($modelQualifications, "[{$i}]employee_qualification_town")->textInput(['maxlength' => 15]) ?>
                            </div>
                            <div class="col-sm-4">
                                <?= $form->field($modelQualifications, "[{$i}]employee_qualification_country")->textInput(['maxlength' => 15]) ?>
                            </div>
                        </div><!-- .row -->
                    </div>
                </div>
            <?php endforeach; ?>
            </div>          
<?php DynamicFormWidget::end(); ?>

So I have 2 problems so far:

  1. When I click [+] on form to duplicate the fieldset, only the first set validates
  2. Datepicker is not working on duplicated fieldset
wbraganca commented 9 years ago

Not working with jui datepicker. Try: http://demos.krajee.com/widget-details/datepicker

loter commented 9 years ago

noval Thank you! Will try to replace jui datepicker with krajee's! What can be the problem with cloned fields validation? any hints?

wbraganca commented 9 years ago

I'm unable to reproduce your problem. I need to see the whole view code for analysis :(

loter commented 9 years ago

Are you trying it on Yii v 2.0.0 or 2.0.1, maybe it makes difference? if you're on 2.0.1 then I will upload entire code, thanks!

loter commented 9 years ago

controllers\EmployeesController.php // here I call actionRegistrationstepone to display the form

<?php
namespace frontend\controllers;

use Yii;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\base\Model;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\data\Pagination;
use frontend\models\Employees;
use frontend\models\EmployeeQualifications;

class EmployeesController extends \yii\web\Controller
{
    public function actionIndex()
    {
        return $this->render('index');
        /*,['model' => new Employees] */
    }

    public function actionRegistrationstepone()
    {
        $modelEmployee = new Employees();
        $modelsQualifications = [new EmployeeQualifications];

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

            $modelsQualifications = Model::createMultiple(Address::classname());
            Model::loadMultiple($modelsQualifications, Yii::$app->request->post());

            // ajax validation
            if (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ArrayHelper::merge(
                    ActiveForm::validateMultiple($modelsQualifications),
                    ActiveForm::validate($modelEmployee)
                );
            }

            // validate all models
            $valid = $modelEmployee->validate();
            $valid = Model::validateMultiple($modelsQualifications) && $valid;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $modelEmployee->save(false)) {
                        foreach ($modelsQualifications as $modelsQualifications) {
                            $modelsQualifications->customer_id = $modelEmployee->id;
                            if (! ($flag = $modelsQualifications->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                    }
                    if ($flag) {
                        $transaction->commit();
                        return $this->redirect(['view', 'id' => $modelEmployee->id]);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        }

        return $this->render('registrationstepone', [
            'modelEmployee' => $modelEmployee,
            'modelsQualifications' => (empty($modelsQualifications)) ? [new Address] : $modelsQualifications
        ]);

        }

/*
        return $this->render('registrationstepone', [
            'modelEmployee' => $modelEmployee,
            'modelsQualifications' => (empty($modelsQualifications)) ? [new EmployeeQualifications] : $modelsQualifications
        ]);
           */

        /*if($model->load(Yii::$app->request->post()) && $model->validate())
        {
        //echo "validated";
        //break;
        return $this->render('Registrationsteptwo',['model'=>$model]);
        } else {
            return $this->render('registrationstepone',['model'=>$model]);
        }
    }*/

}

models\Employees.php

<?php

namespace frontend\models;

use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "employees".
 *
 * @property integer $employee_id
 * @property integer $employee_title
 * @property string $employee_firstname
 * @property string $employee_lastname
 * @property boolean $employee_workpermit
 * @property string $employee_email
 * @property string $employee_phone
 * @property string $employee_mobile
 * @property string $employee_address
 * @property string $employee_town
 * @property integer $employee_country
 * @property string $employee_postcode
 * @property boolean $employee_convict
 * @property string $employee_convict_description
 * @property boolean $employee_med_examination
 * @property boolean $employee_declaration
 * @property integer $employee_nationality
 * @property integer $employee_nino
 * @property boolean $employee_nonino
 * @property string $employee_dob
 * @property integer $employee_marital_status
 * @property string $employee_bank_holder_name
 * @property string $employee_bank_name
 * @property string $employee_bank_sortcode
 * @property string $employee_bank_account_number
 * @property boolean $employee_nobank
 * @property string $employee_kin_firstname
 * @property string $employee_kin_lastname
 * @property string $employee_kin_contactno
 * @property string $employee_kin_relationship
 * @property string $employee_kin_address
 * @property string $employee_kin_postcode
 * @property boolean $employee_details_held
 * @property string $employee_absence_days
 * @property string $employee_absence_periods
 * @property boolean $employee_medication
 * @property boolean $employee_treatment
 * @property boolean $employee_injury
 * @property boolean $employee_disability
 * @property boolean $employee_worktime
 * @property integer $employee_status
 * @property integer $employee_registration_code
 * @property string $employee_password
 * @property integer $employee_registration_date
 * @property integer $employee_edit_date
 * @property string $employee_auth_key
 * @property string $employee_passwordreset_token
 *
 * @property CompetenceLanguages[] $competenceLanguages
 * @property EmployeeAvailability[] $employeeAvailabilities
 * @property EmployeeQualifications[] $EmployeeQualifications
 * @property EmployeeReferences[] $employeeReferences
 * @property TitlesList $employeeTitle
 * @property Countries $employeeCountry
 * @property EmployeeStatuses $employeeStatus
 * @property MaritalStatuses $employeeMaritalStatus
 */
class Employees extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'employees';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['employee_id', 'employee_title', 'employee_firstname', 'employee_lastname', 'employee_email', 'employee_phone', 'employee_mobile', 'employee_address', 'employee_town', 'employee_country', 'employee_postcode', 'employee_convict_description', 'employee_nationality', 'employee_nino', 'employee_dob', 'employee_marital_status', 'employee_bank_holder_name', 'employee_bank_name', 'employee_bank_sortcode', 'employee_bank_account_number', 'employee_kin_firstname', 'employee_kin_contactno', 'employee_kin_relationship', 'employee_absence_days', 'employee_absence_periods', 'employee_status', 'employee_registration_code', 'employee_password', 'employee_registration_date', 'employee_edit_date', 'employee_auth_key'], 'required'],
            [['employee_id', 'employee_title', 'employee_country', 'employee_nationality', 'employee_nino', 'employee_marital_status', 'employee_status', 'employee_registration_code', 'employee_registration_date', 'employee_edit_date'], 'integer'],
            [['employee_workpermit', 'employee_convict', 'employee_med_examination', 'employee_declaration', 'employee_nonino', 'employee_nobank', 'employee_details_held', 'employee_medication', 'employee_treatment', 'employee_injury', 'employee_disability', 'employee_worktime'], 'boolean'],
            [['employee_dob'], 'safe'],
            [['employee_firstname', 'employee_lastname', 'employee_email', 'employee_address', 'employee_bank_holder_name', 'employee_bank_name', 'employee_bank_sortcode', 'employee_bank_account_number', 'employee_kin_firstname', 'employee_kin_lastname', 'employee_kin_contactno', 'employee_kin_relationship', 'employee_kin_address', 'employee_kin_postcode', 'employee_absence_days', 'employee_absence_periods', 'employee_password', 'employee_passwordreset_token'], 'string', 'max' => 255],
            [['employee_phone', 'employee_mobile', 'employee_postcode'], 'string', 'max' => 10],
            [['employee_town', 'employee_auth_key'], 'string', 'max' => 32],
            [['employee_convict_description'], 'string', 'max' => 1024],
            [['employee_registration_code'], 'unique'],
            [['EmployeeQualifications[0]'],'required'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'employee_id' => 'Employee ID',
            'employee_title' => 'Employee Title',
            'employee_firstname' => 'First name',
            'employee_lastname' => 'Last name',
            'employee_workpermit' => 'Employee Workpermit',
            'employee_email' => 'Employee Email',
            'employee_phone' => 'Employee Phone',
            'employee_mobile' => 'Employee Mobile',
            'employee_address' => 'Employee Address',
            'employee_town' => 'Employee Town',
            'employee_country' => 'Employee Country',
            'employee_postcode' => 'Employee Postcode',
            'employee_convict' => 'Employee Convict',
            'employee_convict_description' => 'Employee Convict Description',
            'employee_med_examination' => 'Employee Med Examination',
            'employee_declaration' => 'Employee Declaration',
            'employee_nationality' => 'Employee Nationality',
            'employee_nino' => 'Employee Nino',
            'employee_nonino' => 'Employee Nonino',
            'employee_dob' => 'Employee Dob',
            'employee_marital_status' => 'Employee Marital Status',
            'employee_bank_holder_name' => 'Employee Bank Holder Name',
            'employee_bank_name' => 'Employee Bank Name',
            'employee_bank_sortcode' => 'Employee Bank Sortcode',
            'employee_bank_account_number' => 'Employee Bank Account Number',
            'employee_nobank' => 'Employee Nobank',
            'employee_kin_firstname' => 'Employee Kin Firstname',
            'employee_kin_lastname' => 'Employee Kin Lastname',
            'employee_kin_contactno' => 'Employee Kin Contactno',
            'employee_kin_relationship' => 'Employee Kin Relationship',
            'employee_kin_address' => 'Employee Kin Address',
            'employee_kin_postcode' => 'Employee Kin Postcode',
            'employee_details_held' => 'Employee Details Held',
            'employee_absence_days' => 'Employee Absence Days',
            'employee_absence_periods' => 'Employee Absence Periods',
            'employee_medication' => 'Employee Medication',
            'employee_treatment' => 'Employee Treatment',
            'employee_injury' => 'Employee Injury',
            'employee_disability' => 'Employee Disability',
            'employee_worktime' => 'Employee Worktime',
            'employee_status' => 'Employee Status',
            'employee_registration_code' => 'Employee Registration Code',
            'employee_password' => 'Employee Password',
            'employee_registration_date' => 'Employee Registration Date',
            'employee_edit_date' => 'Employee Edit Date',
            'employee_auth_key' => 'Employee Auth Key',
            'employee_passwordreset_token' => 'Employee Passwordreset Token',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCompetenceLanguages()
    {
        return $this->hasMany(CompetenceLanguages::className(), ['competence_owner' => 'employee_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEmployeeAvailabilities()
    {
        return $this->hasMany(EmployeeAvailability::className(), ['employee_availability_owner' => 'employee_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEmployeeQualifications()
    {
        return $this->hasMany(EmployeeQualifications::className(), ['employee_qualification_owner_id' => 'employee_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEmployeeReferences()
    {
        return $this->hasMany(EmployeeReferences::className(), ['reference_owner_id' => 'employee_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEmployeeTitle()
    {
        return $this->hasOne(TitlesList::className(), ['title_id' => 'employee_title']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEmployeeCountry()
    {
        return $this->hasOne(Countries::className(), ['country_id' => 'employee_country']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEmployeeStatus()
    {
        return $this->hasOne(EmployeeStatuses::className(), ['status_id' => 'employee_status']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEmployeeMaritalStatus()
    {
        return $this->hasOne(MaritalStatuses::className(), ['marital_status_id' => 'employee_marital_status']);
    }

    public static function createMultiple($modelClass, $multipleModels=null)
    {
        $model    = new $modelClass;
        $formName = $model->formName();
        $post     = Yii::$app->request->post($formName);
        $models   = [];
        $flag     = false;

        if ($multipleModels !== null && is_array($multipleModels) && !empty($multipleModels)) {
            $keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
            $multipleModels = array_combine($keys, $multipleModels);
            $flag = true;
        }

        if ($post && is_array($post)) {
            foreach ($post as $i => $item) {
                if ($flag) {
                    if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) {
                        $models[] = $multipleModels[$item['id']];
                    } else {
                        $models[] = new $modelClass;
                    }
                } else {
                    $models[] = new $modelClass;
                }
            }
        }
        unset($model, $formName, $post);
        return $models;
    }
}

models\EmployeeQualifications.php

<?php

namespace frontend\models;

use Yii;

/**
 * This is the model class for table "employee_qualifications".
 *
 * @property integer $idemployee_qualification_id
 * @property integer $employee_qualification_owner_id
 * @property integer $employee_qualification_position
 * @property string $employee_qualification_start_date
 * @property string $employee_qualification_end_date
 * @property string $employee_qualification_reason
 * @property string $employee_qualification_organisation
 * @property string $employee_qualification_town
 * @property integer $employee_qualification_country
 *
 * @property Employees $employeeQualificationOwner
 * @property Positions $employeeQualificationPosition
 * @property Countries $employeeQualificationCountry
 */
class EmployeeQualifications extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'employee_qualifications';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['employee_qualification_owner_id', 'employee_qualification_position', 'employee_qualification_start_date', 'employee_qualification_end_date', 'employee_qualification_country'], 'required'],
            [['employee_qualification_owner_id', 'employee_qualification_position', 'employee_qualification_country'], 'integer'],
            [['employee_qualification_start_date', 'employee_qualification_end_date', 'employee_qualification_reason', 'employee_qualification_organisation', 'employee_qualification_town'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'employee_qualification_id' => 'Qualification ID',
            'employee_qualification_owner_id' => 'Employee Qualification Owner ID',
            'employee_qualification_position' => 'Employee Qualification Position',
            'employee_qualification_start_date' => 'Employee Qualification Start Date',
            'employee_qualification_end_date' => 'Employee Qualification End Date',
            'employee_qualification_reason' => 'Employee Qualification Reason',
            'employee_qualification_organisation' => 'Employee Qualification Organisation',
            'employee_qualification_town' => 'Employee Qualification Town',
            'employee_qualification_country' => 'Employee Qualification Country',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEmployeeQualificationOwner()
    {
        return $this->hasOne(Employees::className(), ['employee_id' => 'employee_qualification_owner_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEmployeeQualificationPosition()
    {
        return $this->hasOne(Positions::className(), ['position_id' => 'employee_qualification_position']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEmployeeQualificationCountry()
    {
        return $this->hasOne(Countries::className(), ['country_id' => 'employee_qualification_country']);
    }

}

views\employees\registrationstepone.php


<?php
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\URL;
use yii\widgets\ActiveForm;
use frontend\models\TitlesList;
use frontend\models\Yesorno;
use frontend\models\EmployeeQualifications;
use wbraganca\dynamicform\DynamicFormWidget;
?>
<?php
$form = ActiveForm::begin(['id'=>'registration-step-1','options'=>['class'=>'form-block']]);
?>
<?php
$titleslist = ArrayHelper::map(TitlesList::find()->orderBy('title_order')->all(), 'title_id', 'title_name');
$yesornolist = ArrayHelper::map(Yesorno::find()->orderBy('yesorno_order')->all(), 'yesorno_id', 'yesorno_name');
$yesornolist = ArrayHelper::map(Yesorno::find()->orderBy('yesorno_order')->all(), 'yesorno_id', 'yesorno_name');
?>
<?= Html::activeDropDownList($modelEmployee, 'employee_title', $titleslist, array('class'=>'form-control','prompt'=>'Please Select Title')) ?>
<?= $form -> field ($modelEmployee,'employee_firstname')  ?>  
<?= $form -> field ($modelEmployee,'employee_lastname') ?>
<?= $form -> field ($modelEmployee,'employee_workpermit')->radiolist($yesornolist,['itemOptions' => ['class' =>'radio-inline']]) ?>

<p>Contact Information</p>
<?= $form -> field ($modelEmployee,'employee_email') ?>
<?= $form -> field ($modelEmployee,'employee_phone') ?>
<?= $form -> field ($modelEmployee,'employee_mobile') ?>
<?= $form -> field ($modelEmployee,'employee_address') ?>
<?= $form -> field ($modelEmployee,'employee_town') ?>
<?= $form -> field ($modelEmployee,'employee_country') ?>
<?= $form -> field ($modelEmployee,'employee_postcode') ?>
<p>Education</p>
<?  
//echo $form -> field ($modelEmployee,'employeeQualifications') 
?>

<?php DynamicFormWidget::begin([
                'dynamicItems' => '#form-qualifications',
                'dynamicItem' => '.form-qualifications-item',
                'model' => $modelsQualifications[0],
                'formId' => 'dynamic-form',
                'formFields' => [
                    'employee_qualification_position',
                    'employee_qualification_start_date',
                    'employee_qualification_end_date',
                    'employee_qualification_reason',
                    'employee_qualification_organisation',
                    'employee_qualification_town',
                    'employee_qualification_country',
                ],
                'options' => [
                    'limit' => 4, // the maximum times, an element can be cloned (default 999)
                ]
            ]); ?>
<div id="form-qualifications">
            <?php foreach ($modelsQualifications as $i => $modelQualifications): ?>
                <div class="form-qualifications-item panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title pull-left">Qualifications</h3>
                        <div class="pull-right">
                            <button type="button" class="clone btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
                            <button type="button" class="delete btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
                        </div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="panel-body">
                        <?php
                            // necessary for update action.
                            if (!$modelQualifications->isNewRecord) {
                                echo Html::activeHiddenInput($modelQualifications, "[{$i}]id");
                            }
                        ?>
                        <?= $form->field($modelQualifications, "[{$i}]employee_qualification_position")->textInput(['maxlength' => 64]) ?>
                        <div class="row">
                            <div class="col-sm-6">
                                <?php echo  $form->field($modelQualifications, "[{$i}]employee_qualification_start_date")->textInput(['maxlength' => 128]) ?>
                                <? //yii\jui\DatePicker::widget(['name' => '[{'.$i.'}]employee_qualification_start_date', 'clientOptions' => ['defaultDate' => '2014-01-01']]) ?>
                            </div>
                            <div class="col-sm-6">
                                <?= $form->field($modelQualifications, "[{$i}]employee_qualification_end_date")->textInput(['maxlength' => 128]) ?>
                            </div>
                        </div><!-- .row -->
                        <div class="row">
                            <div class="col-sm-4">
                                <?= $form->field($modelQualifications, "[{$i}]employee_qualification_reason")->textInput(['maxlength' => 64]) ?>
                            </div>
                            <div class="col-sm-4">
                                <? //$form->field($modelQualifications, "[{$i}]employee_qualification_organisation")->textInput(['maxlength' => 32]) ?>
                            </div>
                            <div class="col-sm-4">
                                <?= $form->field($modelQualifications, "[{$i}]employee_qualification_town")->textInput(['maxlength' => 15]) ?>
                            </div>
                            <div class="col-sm-4">
                                <?= $form->field($modelQualifications, "[{$i}]employee_qualification_country")->textInput(['maxlength' => 15]) ?>
                            </div>
                        </div><!-- .row -->
                    </div>
                </div>
            <?php endforeach; ?>
            </div>          
<?php DynamicFormWidget::end(); ?>

<?php
echo Html::input('button','btn_add','Add More',[
                'onclick'=>'$.post( "' . Yii::$app->urlManager->createUrl(['employeequalifications/create', 'i'=>'']).'"+$("#counter").val(),
                                function( data ){
                                        var val = $("#counter").val();
                                        $( "#counter" ).val( parseInt(val) + 1 );
                                        $( "div#newlyaddedfields" ).append( data );
                                        $( "div#newlyaddedfields" ).wrap( "<div class=\'new\'></div>" );
                                });
                ',//onclick end
]); ?>
<?= yii\jui\DatePicker::widget(['name' => 'employee_qualification_start_date', 'clientOptions' => ['defaultDate' => '2014-01-01']]) ?>
<?php echo Html::hiddenInput('counter',0,['id'=>'counter',]); ?>
<div id="newlyaddedfields">

</div>

<?php
Html::a('Your Link name','controller/action', [
'title' => Yii::t('yii', 'Close'),
    'onclick'=>"$('#close').dialog('open');
     $.ajax({
    type     :'POST',
    cache    : false,
    url  : 'controller/action',
    success  : function(response) {
        $('#close').html(response);
    }
    });return false;",
                ]);

?>

 <?= Html::a('Add', null, [
        'class' => 'btn btn-success',
        'data' => [
            'toggle' => 'reroute',
            'action' => Url::toRoute(['addresses/create', 'employee_id' => $modelEmployee->employee_id])
        ]
    ]) ?>

    <?= Html::a('Remove', null, [
        'class' => 'btn btn-danger',
        'data' => [
            'toggle' => 'reroute',
            'action' => Url::toRoute(['addresses/delete', 'employee_id' => $variable->employee_id])
        ]
    ]) ?>

<p>Employment in the last two years</p>

<p>Languages</p>

<p>Additional information</p>
<div class="form-group">
        <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
    </div>
<?php
ActiveForm::end();
?>
wbraganca commented 9 years ago

change

'formId' => 'dynamic-form'

To

'formId' => 'registration-step-1'
loter commented 9 years ago

It is working!!!

Sorry, stupid me :)

Thank you so much for your time!!!

wbraganca commented 9 years ago

Suggestions:

Remove the "createMultiple" method of model "Employees" and add in a class that inherits from the \yii\base\Model.

Example:

Directory: app\base\Model.php

<?php

namespace app\base;

use Yii;
use yii\helpers\ArrayHelper;

class Model extends \yii\base\Model
{
    public static function createMultiple($modelClass, $multipleModels=null)
    {
        $model    = new $modelClass;
        $formName = $model->formName();
        $post     = Yii::$app->request->post($formName);
        $models   = [];
        $flag     = false;

        if ($multipleModels !== null && is_array($multipleModels) && !empty($multipleModels)) {
            $keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
            $multipleModels = array_combine($keys, $multipleModels);
            $flag = true;
        }

        if ($post && is_array($post)) {
            foreach ($post as $i => $item) {
                if ($flag) {
                    if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) {
                        $models[] = $multipleModels[$item['id']];
                    } else {
                        $models[] = new $modelClass;
                    }
                } else {
                    $models[] = new $modelClass;
                }
            }
        }
        unset($model, $formName, $post);
        return $models;
    }
}
demigorian commented 9 years ago

I have problem with update in dynamic forms. Please help me...I'm beginner in php This is my actionupdate

public function actionUpdate($id) {

    $model = $this->findModel($id);
    $modelsCtel = $model->ctels;
    $modelsDvr = $model->dvrs;

    if ($model->load(Yii::$app->request->post()) && $model->save()) {

        $oldIDs = ArrayHelper::map($modelsCtel, 'id', 'id');
        $oldIDs = ArrayHelper::map($modelsDvr, 'id', 'id');

        $modelsCtel = Model::createMultiple(Ctel::classname(), $modelsCtel);
        Model::loadMultiple($modelsCtel, Yii::$app->request->post());

        $modelsDvr = Model::createMultiple(Dvr::classname(), $modelsDvr);
        Model::loadMultiple($modelsDvr, Yii::$app->request->post());

        $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsCtel, 'id', 'id')));
        $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsDvr, 'id', 'id')));
        // ajax validation

        // validate all models
        $valid = $model->validate();
        $valid = Model::validateMultiple($modelsCtel) && $valid;
        $valid = Model::validateMultiple($modelsDvr) && $valid;
        if ($valid) {
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                if ($flag = $model->save(false)) {

                    if (! empty($deletedIDs)) {
                        Ctel::deleteAll(['id' => $deletedIDs]);
                    }

                    if (! empty($deletedIDs)) {
                        Dvr::deleteAll(['id' => $deletedIDs]);
                    }

                    foreach ($modelsCtel as $modelCtel) {
                        $modelCtel->id_client = $model->id;
                        if (!($flag = $modelCtel->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }

                    foreach ($modelsDvr as $modelDvr) {
                        $modelDvr->id_client = $model->id;
                        if (!($flag = $modelDvr->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }
                }
                if ($flag) {
                    $transaction->commit();
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            } catch (Exception $e) {
                $transaction->rollBack();
            }
        }
    } else {
        return $this->render('update', [
                    'model' => $model,
                    'modelsCtel' => (empty($modelsCtel)) ? [new Ctel] : $modelsCtel,
                    'modelsDvr' =>(empty($modelsDvr)) ? [new Dvr] : $modelsDvr
        ]);
    }
fullflash commented 3 years ago

customer_id is required field and will fail on line Model.validateMultiple