This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

grandpa
grandpa

Hi, I need your help on how to put a validation on a form field relationship. I've been spending a few hours already but don't have any luck.

So, I have 2 models Meta and Page. In which page model has one meta. So what I'm planning to do is to put a validation of one the of the field from Meta model which is the title

Page.php Model

  public $rules = [
      'page_name' => 'required',
      'slug' => 'required',
      'title' => 'required',
  ];  

  public $hasOne = [
      'meta' => ['proj\Meta\Models\Meta', 'key' => 'page_id'],
  ];

Page fields.yml

  fields:
      page_name:
          label: Page Name
          span: auto
          type: text
          required: 1
      slug:
          label: Slug
          span: auto
          type: text
          required: 1
          readOnly: true
          tab: 'Page Url'
      'meta[title]':
          label: 'Meta Title'
          span: auto
          type: text
          required: 1
      'meta[description]':
          label: 'Meta Title'
          span: auto
          type: text

in my validation $rules it seems the title field is not working properly. Would be greatly appreciated if someone share an idea about the validation. Thank you

mjauvin
grandpa
grandpa

Hi @mjauvin thank you for your reply, i tried using this

 `'meta.title' => 'required'`

seems still have no luck, still showing the error like The title field is required, even though the field has a value

mjauvin
mjauvin

Ok, so this is only for jsonable fields within the model, not for relations.

JeffGoldblum
JeffGoldblum

You have to set the validation rules on the Meta model itself.

So

$rules = [
    'title' => 'required',
    'description' => 'required',
];
grandpa
grandpa

@LukeTowers, it can be done using your way. However, the Meta model is sharable across the plugin and there will be an issue with other plugins that use that Model, which having that field but is not required or mandatory. So, I'm thinking if possible to have the validation on that field in my Page model only.

mjauvin
mjauvin

Maybe you could add the rule to the Meta model dynamically using the Pages controller beforeValidate method?

Or manually check this like in this forum thread:

https://octobercms.com/forum/post/conditional-backend-form-input-validation-on-other-input-field

1-7 of 7

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.