2

My plugin has a custom element type. The element type uses a standard "title" field, implemented by MyElementType::hasTitles() returning true.

In addition, my element type contains a few hard-coded fields. The whole plugin has been built out and working great, I'm very happy with how all of the components interact.

However, I'm trying to refine the validation of when an element is saved. It's easy to make a field required by simply adding 'required' => true when defining the field in my Record. And when a user attempts to save an element without filling in that field, the proper error message will be triggered and displayed in my template.

But here's the catch...

If the user leaves empty both the title field and my hard-coded field, only one of them will display an error message at a time. Specifically, only the hard-coded field will display the error message first. Once that has been filled in, the title error message will be triggered on the second submission.

What am I missing? Is there a specific way to merge these error messages together so that they are both returned to the template at the same time?

4

You can pass the element off to ContentService::validateContent() in the event that it doesn't pass the record’s validation, just to get those errors mixed into the element as well.

if (!$record->validate())
{
    // Copy the record's errors over to the element model
    $element->addErrors($record->getErrors());

    // Might as well validate the content as well,
    // so we get a complete list of validation errors
    if (!craft()->content->validateContent($element))
    {
        // Copy the content model's errors over to the element model
        $element->addErrors($element->getContent()->getErrors());
    }

    return false;
}
  • Brilliant, this worked like a charm. Thanks Brandon! – Lindsey D Oct 31 '14 at 5:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.