Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validation is not working with many_many Multi Class Adding #156

Open
bhofstaetter opened this issue Jul 23, 2016 · 2 comments
Open

Validation is not working with many_many Multi Class Adding #156

bhofstaetter opened this issue Jul 23, 2016 · 2 comments

Comments

@bhofstaetter
Copy link

I'm using multi class adding on a page to add data objects to a many_many relation.
The data object's getCMSValidator() method only gets called after the data object is added to the relation. So the validation only takes place after the object is written and if you hit the save button again.

@bhofstaetter
Copy link
Author

bhofstaetter commented Jul 24, 2016

for everyone else with this issue. a workaround would be to use the validate() methode like that

  public function validate() {
    $result = parent::validate();

    if(!$this->ID) {
      $manyRelations = array_merge($this->many_many(), $this->has_many());
      $oneRelations = $this->has_one();
      $fields = $this->getCMSValidator()->getRequired();

      foreach($fields as $field) {
        if(array_key_exists($field, $manyRelations)) {
          if(!$this->$field()->first()) {
            $result->error('"' . $field . '" muss ausgefüllt werden');
          }
        } else if (array_key_exists($field, $oneRelations)) {
          if(!$this->$field()->exists()) {
            $result->error('"' . $field . '" muss ausgefüllt werden');
          }
        } else {
          if(!$this->$field) {
            $result->error('"' . $field . '" muss ausgefüllt werden');
          }
        }
      }
    }

    return $result;
  }

Updated my workaround to cover has_many, many_many and has_one realtions

@user121216
Copy link

In my case your workaround is not working. The $manyRelations are always empty. I'm using silverstripe 3.2.
getCMSValidator is partially working because it detects the missing relations. But I still got a strange behaviour. Validations in validate() will be only executed if getCMSValidator is successfully.
E.g. the user got an error for missing relation (getCMSValidator) and after fixing this, the user got further error messages (validate()).

Can somebody describe a correct implementation to use validate() and a if condition for non empty relation objects?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants