Struggling a bit here - have created a custom plugin where I want to validate form submission against a predefined model before saving to the database. All pretty straightforward so far …
However, if I try to use native (Yii 2) validation then a record is saved regardless of whether it is valid or not. For example, if I set the model rules as follows:
public function rules()
{
return [
[['formName'], 'required'],
[['formName'], 'string', 'min' => 1, 'max' => 255, 'skipOnEmpty' => false]
];
}
The record is saved, even if $model->formName
is empty. For example, see the following Controller code:
public function actionUpdate()
{
$this->requirePostRequest();
$request = Craft::$app->getRequest();
$site = Craft::$app->getSites()->getCurrentSite();
$formName = $request->getBodyParam('formName');
$formId = $request->getBodyParam('formId');
// get ID (if exists)
if ($formId) {
$formRecord = FormRecord::find()
->where(['id'=>$formId])->one();
// if count == null return false
} else {
$formRecord = new FormRecord;
}
$formRecord->formName = $formName;
$formRecord->siteId = $site->id;
if ($formRecord->validate()) {
…
The code will always validate - even if the formName is empty. This seems a bit crazy to me - am I misunderstanding something about Yii validation rules here?
Help/thoughts appreciated,
Cole