4

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

Cole Henley
  • 1,741
  • 11
  • 20

2 Answers2

1

Since Craft 3.4.0 you should be using defineRules() over rules() in your model classes.

Models should override this method instead of [[rules()]] so [[EVENT_DEFINE_RULES]] handlers can modify the class-defined rules.

See https://github.com/craftcms/cms/blob/d2b867f601cd75a33a22a016d8ea823bdda614e4/src/base/Model.php#L127-L141

But that doesn't explain why your rules are not working. Be sure to place the defineRules() method on the record class.

use craft\db\ActiveRecord;

class FormRecord extends ActiveRecord { public function defineRules() { return [ [['formName'], 'required'], [['formName'], 'string', 'min' => 1, 'max' => 255], ]; } }

Then if $formRecord->formName is empty, $formRecord->validate() should evaluate to false.

Ben Croker
  • 7,341
  • 26
  • 55
0

I am a beginner at craft cms,but I think these would help you:- 1.install the plugin guest entries and look at their code 2.look at this article

jamesSeb
  • 81
  • 6