Question

I'm writing a module which registers a subscriber to our internal newsletter system, by using the stock Newsletter block in Magento.

I'm creating an observer on the controller_action_predispatch_newsletter event. I intend to check at this point whether a user is already subscribed to our system and if they are, giving a validation error on the email field to say the user exists.

I've found countless questions about adding the form validation classes and data attributes, that is fine, this works as expected. It's this post submit state which I want to check. If the user does exist in our system, I don't want to then subscribe to them in Magento.

My question is, how if the user does exist in our system, do I add a validation error to the email field on the front end?

I've included all the information I can, is this possible, or am I taking the wrong approach here?

Thanks in advance.

Was it helpful?

Solution

Does it have to use the form validation? I wouldn't bother with this, as you are just using a single form field. You can just redirect to the previous page and use MessageManager class to add an error message that will display on the frontend (e.g. $this->messageManager->addErrorMessage(__('This email address is already subscribed'));. Then redirect the user. This is actually what the native Magento newsletter controller does (see \Magento\Newsletter\Controller\Subscriber\NewAction::execute).

Will you be posting to the native controller (above)? You could perhaps do a before plugin on the execute method instead of using an observer. If you are writing your own controller method for the posted form values, you could model it after the native one. Just a thought. Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top