Home > Enterprise >  Yii2 getting error Area must be string when selecting a text from dropdown
Yii2 getting error Area must be string when selecting a text from dropdown

Time:10-27

I am working on yii2.

I have a below field in my _form

$form->field($model, 'area_name')
    ->widget(Select2::className(),[
            'data' => \common\models\AllowArea::toAreaArrayList(),
            'options' => ['placeholder'=>'Select Area'],
        'pluginOptions' => [
            'allowClear' => true,
            'multiple' => true
        ],
    ]);
        
?>

When I am trying to select from it I am getting

Area Name must be a string.

GUI

enter image description here

Below is my validation rule

public function rules()
{
    return [
        [['user_id','created_by','updated_by'], 'integer'],
        [['area_name','user_id','salesman_code','city_name'], 'required'],
        [['area_code', 'user_name'], 'string', 'max' => 50],
        [['created_at'],'safe'],
        [['area_name', 'salesman_code', 'salesman_name'], 'string', 'max' => 100],
        [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
    ];
}

Function

public static function toAreaArrayList()
{
    $sds = Yii::$app->sds->createCommand("Select * from Area")->queryAll();
   
    return ArrayHelper::map(Yii::$app->sds->createCommand("select distinct AreaNameFull from Area where AreaCode NOT IN ('020201001','020202001')")->queryAll(),'AreaNameFull',function($sds, $defaultValue){
        return $sds['AreaNameFull'];
    });
}

Any help would be highly appreciated.

CodePudding user response:

I just removed area_name from [['area_name', 'salesman_code', 'salesman_name'], 'string', 'max' => 100], to [[ 'salesman_code', 'salesman_name'], 'string', 'max' => 100], and it's start working.

CodePudding user response:

Select 2 widget initializes in multiple mode. That means that the result is an array.

If it's not desired behavior, just remove 'multiple' => true.

Otherwise, the field rule of the form should be

['area_name', 'each', 'rule' => ['string', 'max' => 100]],
  • Related