I want to check if the categoryid given is an existing category. I've tried several values as the target attribute, but I can't get it working so far.
When I execute the query as is, it returns the correct value for what I am trying to add.
public function rules()
{
return [
[['categoryid'], 'integer'],
['categoryid', 'exist', 'targetAttribute' => FaqCategory::findOne(['id=:id', ['id'=>'categoryid']])['id']],
[['question', 'answer'], 'required'],
[['answer'], 'string'],
[['question'], 'string', 'max' => 255]
];
}
I stumbled upon targetClass. However this time around I receive Class 'FaqCategory' not found. Class is to be found under the same namespace.
['categoryid', 'exist', 'targetClass' => 'FaqCategory']
You have to use class name with namespace, it should be something like :
['categoryid', 'exist', 'targetClass' => '\app\models\FaqCategory']
Or
['categoryid', 'exist', 'targetClass' => FaqCategory::className()]
http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#exist
Got the answer thanks to soju. Just needed to add the targetAttribute to compare the categoryid to the id of the category.
['categoryid', 'exist', 'targetClass' => '\app\models\FaqCategory', 'targetAttribute' => 'id'],
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With