0

I have a model Printer, a model Category, and a model for the relation between the two models CategoryPrinterRel

In the CategoryPrinterRel model I need a unique validator between the $category_id, and the client of the printer $printer->client_id

Up till now I have tried

public function rules()  
{
    [['category_id', $this->printer->client_id], 'unique', 'targetAttribute' => ['category_id']]
}

Is there any other way to do this though? The problem with the method I'm using is that when the printer object is empty, trying $this->printer->client_id gives an error

mrateb
  • 2,317
  • 5
  • 27
  • 56
  • The first item of your rules should be an array of attributes (their names in string form). `$this->printer->client_id` is a *value* (probably an integer?). That's never going to work. – mae Dec 06 '17 at 13:20
  • I do have those rules, but I omitted them here for brevity. And it worked, but as I mentioned it's giving me errors when printer is empty – mrateb Dec 06 '17 at 14:53
  • I'm trying to find an alternative way – mrateb Dec 06 '17 at 14:54

1 Answers1

1

I was looking for something more elegant, or built in. For now I have opted for a custom validator however. In the model:

public function rules()
{
    return [
        [['category_id', 'printer_id'], 'integer'],
        [['printer_id', 'category_id'], 'required'],
        [['cat_id'],'validateUniquenessOnClient']
    ];
}

public function validateUniquenessOnClient($attribute, $params, $validator)
    {
        $isPrinterUniqueOnClient = DbPrinterRepository::IsPrinterCatRelUniqueOnClient($this->category_id, $this->printer_id);
        if(!$isPrinterGroupUniqueOnClient)
        {
            $this->addError($attribute, "There is already a printer using that category ({$this->cat->name}).");
        }

    }
mrateb
  • 2,317
  • 5
  • 27
  • 56