0

I work in a functionality in which I must validate some fields before saving, if a condition is not met I must indicate abort the save process, according to the documentation of the onContentBeforeSave event I do this by returning false, this works fine, but I would like to add a personalized message. Right now when return false, the following message is displayed in the view

enter image description here

I understand after the colon a personalized message is expected. How I do this?

This is the plugin code I am trying

<?php

defined( '_JEXEC' ) or die( 'Restricted access' );

class plgContentMyPlugin extends JPlugin
{
    public function onContentBeforeSave($context, &$article, $isNew, $data)
    {
        if ($context === 'com_content.article') {
            $field1 = $data['com_fields']['field1'];
            $field2 = $data['com_fields']['field2'];

            if (!empty($field1) && empty($field2)) {
                return false; // here, how can I attach a message?
            }

            $date = strtotime($field1);
            $now = time();

            if ($date > $now) {
                return false; // here, how can I attach a message?
            }
        }

        return true;
    }
}

Thanks in advance

2

1 Answer 1

2

You can throw an Exception:

if ($date > $now)
{
    throw new RuntimeException(JText::_('PLG_CONTENT_MYPLUGIN_SOME_ERROR'));
}

Or use setError() on the table object:

if ($date > $now)
{
    $article->setError(JText::_('PLG_CONTENT_MYPLUGIN_SOME_ERROR'));

    return false;
}
1
  • user615274, if you look at /libraries/src/MVC/Model/AdminModel.php at line 1273 you can see where the message in @Sharky 's second suggestion is going to be retrieved. Or at line 1294 you can see the Catch that will display the exception message set in his first suggestion.
    – Irata
    Commented Oct 29, 2019 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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