[[+content_image]]
M
M
Michael2016-07-15 20:56:18
Yii
Michael, 2016-07-15 20:56:18

Is this validation rule ok?

Models usually have single-level data. Difficulties arise on several levels.
Is this method of validation normal?

<?php

class Items
{
    public function rules()
    {
        return [
            [['items'], 'checkItem']
        ];
    }

    protected function checkItem()
    {
        $status = (is_array($this->items) || is_object($this->items)) && $this->items;

        if ($status) {
            foreach ($this->items as $item) {
                $itemModel = new Item;
                
                $status = ($itemModel->load($item, '') && $itemModel->validate());

                if (!$status) {
                    break;
                }
            }
        }

        return $status;
    }
}

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Timofeev, 2016-07-15
@webinar

1. Instead

public function rules()
    {
        return [
            ['items'], 'checkItem'
        ];
    }

maybe
public function rules()
    {
        return [
            [['items'], 'checkItem']
        ];
    }

2. function checkItem() always returns the same result for you, what's the point?
3.
foreach ($this->items as $item) {
                $item = new Item;

it makes sense to sort through $item if you immediately replace its value with a new empty object. Yes, and probably so new Item ()
So, as for me - complete nonsense

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question