1

I have a registration form and its custom validation in PHP plugin code.

However, the validation works when user set a new password. I supposed that $event->isNew is good to detect if it is a new user registration or not, but the element does not work. Craft says it is unknown property.

Could you tell me how to detect the kinds of submission?

// Registration Form
$request = Craft::$app->getRequest();
Event::on(
    User::class,
    Element::EVENT_BEFORE_VALIDATE,
    function (Event $event) use($request) {
        // If a user already logged in we are not on the public registration page
        if (Craft::$app->getUser()->getIdentity()) return;

        if (!$event->isNew) return;

        // Do the custom validation
        if (!$event->sender->firstName) {
            $event->sender->addError('firstName', Craft::t('yii', '{attribute} cannot be blank.', [ 'attribute' => Craft::t('app', 'First Name') ]));
            $event->isValid = false;
        }
...
2

First, you should test the sender property pointing to the User element.

Second, there's no such property as isNew in that case.

However, you could test that user is new given that its ID won't be set in case the user has not been saved yet.

Something like:

Event::on(
    User::class, // \craft\elements\User
    User::EVENT_BEFORE_VALIDATE,
    function (\yii\base\ModelEvent $event) {
        $sender = $event->sender;
        Craft::debug("User " . ($sender->id ? "already exists" : "is new"), __METHOD__);
    }
);
0

Thank you for answering my question. Since I would like to use if user is new or not later, I edited the code like this.

$sender_id = $event->sender->id;
if ($sender_id) $is_new = false; else $is_new = true;

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.