ActiveForm Validation on Dropdownlist with ForeignKey

Hi,

i have a model this using a relation to a country table:


<?php


namespace app\models;


use Yii;

use yii\helpers\ArrayHelper;


/**

 * This is the model class for table "contacts".

 *

 * @property integer $id

 * @property string $datum

 * @property string $firstname

 * @property string $lastname

 * @property string $address

 * @property string $plz

 * @property string $city

 * @property integer $country

 * @property string $email

 * @property string $tel

 * @property string $tel2

 * @property string $mobil

 * @property string $skype

 * @property string $facebook_name

 * @property string $type

 * @property string $hinweise

 *

 * @property ContactNotes[] $contactNotes

 * @property Countries $country0

 * @property Interests[] $interests

 * @property Partners[] $partners

 */

class Contacts extends \yii\db\ActiveRecord

{

	public function beforeSave($insert) {

		if ($insert)

			$this->country = intval($this->country);

		return parent::beforeSave($insert);

	}

    /**

     * @inheritdoc

     */

    public static function tableName()

    {

        return 'contacts';

    }


    /**

     * @inheritdoc

     */

    public function rules()

    {

        return [

            [['datum', 'firstname', 'email'], 'required'],

            [['country'], 'integer'],

	        [['datum'], 'string'],

            [['hinweise'], 'string'],

            [['firstname', 'lastname', 'address', 'city', 'email', 'tel', 'tel2', 'mobil', 'skype', 'facebook_name'], 'string', 'max' => 255],

            [['plz'], 'string', 'max' => 10],

            [['type'], 'string', 'max' => 45],

            [['email'], 'unique'],

            [['country'], 'exist', 'skipOnError' => false, 'targetClass' => Countries::className(), 'targetAttribute' => ['id']],

        ];

    }


    /**

     * @inheritdoc

     */

    public function attributeLabels()

    {

        return [

            'id' => 'ID',

            'datum' => 'Datum',

            'firstname' => 'Firstname',

            'lastname' => 'Lastname',

            'address' => 'Address',

            'plz' => 'Plz',

            'city' => 'City',

            'country' => 'Country',

            'email' => 'Email',

            'tel' => 'Tel',

            'tel2' => 'Tel2',

            'mobil' => 'Mobil',

            'skype' => 'Skype',

            'facebook_name' => 'Facebook Name',

            'type' => 'Type',

            'hinweise' => 'Hinweise',

        ];

    }


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getContactNotes()

    {

        return $this->hasMany(ContactNotes::className(), ['c_id' => 'id']);

    }


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getCountry0()

    {

        return $this->hasOne(Countries::className(), ['id' => 'country']);

    }


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getInterests()

    {

        return $this->hasMany(Interests::className(), ['c_id' => 'id']);

    }


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getPartners()

    {

        return $this->hasMany(Partners::className(), ['c_id' => 'id']);

    }


    /**

     * @inheritdoc

     * @return ContactsQuery the active query used by this AR class.

     */

    public static function find()

    {

        return new ContactsQuery(get_called_class());

    }

	public function getCountryDropDown() {

		$drop = Countries::find()->orderBy('name')->asArray()->all();

		return ArrayHelper::map($drop,'id','name');

	}

}



The _form for create a contact:


<?php


use yii\helpers\Html;

//use yii\widgets\ActiveForm;

use yii\helpers\ArrayHelper;

use app\models\Countries;

use kartik\form\ActiveForm;


/* @var $this yii\web\View */

/* @var $model app\models\Contacts */

/* @var $form yii\widgets\ActiveForm */

?>


<div class="contacts-form">


    <?php

    $form = ActiveForm::begin([

	    'type' => ActiveForm::TYPE_HORIZONTAL,

	    'formConfig' => ['labelSpan' => 2, 'deviceSize' => ActiveForm::SIZE_SMALL],

    ]);

    ?>


    <?= $form->field($model, 'datum')->textInput() ?>


    <?= $form->field($model, 'firstname')->textInput(['maxlength' => true])->label('Vorname',['class' => 'control-label col-sm-2']) ?>


    <?= $form->field($model, 'lastname')->textInput(['maxlength' => true])->label('Nachname') ?>


    <?= $form->field($model, 'address')->textInput(['maxlength' => true])->label('Adresse') ?>


    <?= $form->field($model, 'plz')->textInput(['maxlength' => true,'data-inputmask' => "'mask':'00000'",'class' => 'form-control mask'])->label('PLZ') ?>


    <?= $form->field($model, 'city')->textInput(['maxlength' => true])->label('Ort') ?>


    <?= $form->field($model, 'country')->dropDownList($model->getCountryDropDown(), [

	    'prompt' => 'Land auswählen',

    ])->label('Land') ?>


    <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>


    <?= $form->field($model, 'tel')->textInput(['maxlength' => true,'data-inputmask' => "'mask':'(0034) 999-999999'",'class' => 'form-control mask']) ?>


    <?= $form->field($model, 'tel2')->textInput(['maxlength' => true,'data-inputmask' => "'mask':'(0034) 999-999999'",'class' => 'form-control mask']) ?>


    <?= $form->field($model, 'mobil')->textInput(['maxlength' => true,'data-inputmask' => "'mask':'(0034) 999-999999'",'class' => 'form-control mask']) ?>


    <?= $form->field($model, 'skype')->textInput(['maxlength' => true]) ?>


    <?= $form->field($model, 'facebook_name')->textInput(['maxlength' => true]) ?>


    <?= $form->field($model, 'type')->textInput(['maxlength' => true])->label('Typ') ?>


    <?= $form->field($model, 'hinweise')->textarea(['rows' => 6]) ?>


    <div class="form-group">

        <?= Html::submitButton($model->isNewRecord ? 'Anlegen' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    </div>


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


</div>



My Problem:

If I want save a new contact, the validation of Country everytimes are failed, but into the html code of the select this are correct (<option value="1">Germany</option>).

What’s wrong here?

P.S.: All was created with gii, without the dropdown-list and the methode getCountryDropDown().

The value of selected item is the id of the record you have on the db?

Yes Sir

Ok what kind of validation you need?Should you check if it is empty or not or what else?

Normally it should validate if the Country ID exists and not empty, no more.

You send an array for targetAttribute, but according to the documentation you should use a string for single attribute and, if you are using advanced app, you can try to use the extended way to call the model




  [['country'], 'exist', 'skipOnError' => false, 'targetClass' => \app\folder\models\Countries, 'targetAttribute' => 'id'],




If in this way it still doesn’t work, maybe you could need a custom validation

Thanks, you are right. I have change it to String (not array) and now works.

Thanks