M
M
Maxim2018-06-15 18:13:06
Yii
Maxim, 2018-06-15 18:13:06

How is it correct to model a strange array =)?

Hello everyone!))
I am doing MultipleInput for the user_id field. I have an array like this

[
    'rang_id' => '1'
    'discipline_id' => '1'
    'nomination_id' => '1'
    'category_id' => '1'
    'users' => ''
    'user_id' => [
        0 => '1'
        1 => '2'
        2 => '3'
    ]
]

Tell me how to save such an array so that it passes all possible validation in the rules?
public function actionCreate()
    {

        $model = new RegEvent([
            'number'=> RegEvent::setNumber(),
            'event_id' => RegEvent::getEventId()
        ]);

        $model->scenario = $model::SCENARIO_FRONTEND;

        if ($model->load(Yii::$app->request->post())) {
            if (is_array($model->user_id)){
                foreach ($model->user_id as $user_id) {
                    $model->user_id = $user_id;
                    $model->rang_id;
                    $model->save();
                }
            }
                return $this->redirect(['index']);
        }

        if (Yii::$app->request->isAjax){
            return $this->renderAjax('_form', [
                'model' => $model,
            ]);

        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-06-15
@myks92

if (is_array($model->user_id)){
                foreach ($model->user_id as $user_id) {
                    $model->user_id = $user_id;
                    $model->rang_id;
                    $model->save();
                }
            }

You just saved the model n times, each time changing the user_id in it. What's the point? As a result, your user_id will have the last element of the array. And what it does in the cycle $model->rang_id;, it does not change, in any case it must be taken out of the cycle. You decide what you want to get. If you need to store an array there, then it might be worth using json (doing it in beforeSave and back in afterFind), if with a string, then you need to combine the array into an implode string , maybe you need 1 more table where regEvent_id | user_id
What exactly do you need?
Regarding array validation, there is yii\validators\EachValidator
and it confuses me
'users' => '',
'users' => [
        0 => '1'
        1 => '2'
        2 => '3'
    ]

how did you get two identical keys? In addition, you got it $users, and you sort it out in a cycle $model->user_id, as I understand it, there should have been $model->usersor Yii::$app->request->post('users')
In general, the code here is strange, but the array is quite normal. I think we should finish for today and go have a drink. You are not yesterday, but here it’s just awful. Need to rest.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question