Paul Schröder
Paul Schröder

Reputation: 1540

How can I validate two models in one Form separately via ajax

I need to implement the following work flow.

  1. User types in an url
  2. User clicks "validate"-button
    • url is validated (not empty and existent) via ajax.
    • If the url is valid, some informations should be parsed automatically from the given site and fill some form fields on the same page.
    • Those form fields also needs to be validated (some fields are required) via ajax.
  3. If all required fields are filled the user can hit a save button. Elsewise he is prompted to fill out all remaining required fields.

What is the best way to achieve this? The url field and the form fields are two diffrent models in one form, cause for saving I need both.

Most of the work flow I already implemented, but I`am not sure if this is the correct way. I enabled the ajax validation for my form. The url field is validated correctly, but the other fields not eveny trigger the validation. Maybe cause those fileds are packed in an bootstrap active form?

After clicking the "validate"-button I trigger an own ajax request, where I validate the url manually. If its valid I parse the page and return all found informations, elsewise I return the errors. The success method than shows the errors or fill the other form fields. Is there a way to trigger the yii ajax validation programmatically before send my own ajax request.

Now I´am stucked with the ajax validation of the other form fields. Submit, validate and save on success works well. But I want a validation without submitting. Do I have to implement my own ajax request and response handling or is there a way to use some yii built-in functionality?

Upvotes: 0

Views: 164

Answers (1)

Jonast92
Jonast92

Reputation: 4967

Let's say you have a form with some fields:

  • Make the save button be disabled.
  • Have a listener that listens for changes in the fields.
  • Have a unique function that can validate each field and make it return a boolean.
  • Enable the save button if the boolean values for all the validations are true.

It's also a good practise to

  • have a div that you can load messages into, so that the user is aware of his mistakes / non-valid fillouts.

And note that

  • You don't need Ajax unless you're performing some database functions in the backend.
  • You can have a validate button instead of the listeners if you want.

Am I misunderstanding you?

Upvotes: 1

Related Questions