I’m trying to add validation to recipes when they’re submitted. The recipe category needs to be selected from a select box. I tried adding an id to the form element (select box) with some jquery and I tried adding the “required” key word like you can do for form fields but neither worked. Also when I use ->notEmptyString(‘directions’) for another form element, it doesn’t let the form be submitted even when the field is filled in. ‘directions’ is a text area and when I add text to it, it still doesn’t submit. I’m not able to add the “required” key word to the text area either.
In my RecipesTable.php
public function validationDefault(Validator $validator): Validator
when I use ->notEmptyString(‘category_id’);, the form can’t be submitted even when the category_id is given. When I use ->allowEmptyString(‘category_id’);, the form can be submitted but obviously there’s no validation for the category select box.
required are two different things.
notEmptyString checks that if a value is present, it is not empty. It does not require that a value be present. For that, you need
->requirePresence('category_id', 'create'). This, in conjunction with
notEmptyString should guarantee that there is a category_id value in the submitted data, and that it is not blank.
As for what’s going wrong with directions, I can’t say.
notEmptyString should definitely allow it through when you have put text there. I guess check that you haven’t got a typo in a field name anywhere that’s messing this up.
I put aside the task with “category_id” for now and concentrated on the textarea field called “directions.”
I commented out all of the rest of the code in case there was an error, but I still couldn’t submit the form even when the “directions” textarea was filled in. I’m using ckEditor with the ID of “editor”. This line of code still never let the form submit even when the textarea was filled out:
->notEmptyString('directions'); I tried adding rules for minimum length and tried to find out what scalar even meant, but to no avail. My directions field in the database has the data type of TEXT.
directions “accessible” in your entity class? If not, then whatever you send in that field will never make it into your entity, and the validation will of course always fail.
If it is, you’ll need to show us your form code for that field, and/or a debug dump of the data that is being received by your controller.