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

Cant get addError to work $submission->addError('message.body', 'Links are not allowed in the message'); #207

Closed
amityweb opened this issue May 14, 2021 · 2 comments
Labels

Comments

@amityweb
Copy link

amityweb commented May 14, 2021

Does the addError on a custom field actually work? Here is my code to check if links are in the body and if so to show an error:

Event::on(Submission::class, Submission::EVENT_AFTER_VALIDATE, function(Event $e)
{
	$submission = $e->sender;

	if( isset($submission->message['body']) )
	{
		$message = $submission->message['body'];
		if( strpos($message, 'https:') !== false || strpos($message, 'http:') !== false || strpos($message, 'www.') !== false )
		{
			$submission->addError('message.body', 'Links are not allowed in the message');
		}
	}

});

Then in the template:

<textarea rows="6" cols="40" id="message" name="message[body]" placeholder="{{ strings('Inquiry') }}" required>{{ message.message.body ?? '' }}</textarea>
{{ message is defined and message ? errorList(message.getErrors('message.body')) }}

Although the flash error message appears saying there are errors with the form, the specific error after the text area is not showing. I was referring to the documentation on The afterValidate event, but using my body field instead of Phone in the example. Cant see any other differences.

The $submission object does not contain the above error

If I leave my email blank I can see the built in error for email is required. So it seems this is just not working:
$submission->addError('message.body', 'Links are not allowed in the message');

@amityweb amityweb added the bug label May 14, 2021
@jamiematrix
Copy link

Came here to ask a similar question.

It seems that the default required fields (body, fromEmail) have set error messages. I haven't delved into the source yet, but will try to remember to update this comment when I do

@i-just
Copy link
Contributor

i-just commented Mar 7, 2024

Hi, apologies for the late reply!

I just tested this with the latest versions (Craft CMS 3.9.11 + Contact Form 2.5.2 and Craft CMS 4.8.1 + Contact Form 3.0.1), and in both cases, adding an error to a custom field (via addError()) works as expected.

I will close this, but if you still have issues with those not showing, please don’t hesitate to get in touch.

@i-just i-just closed this as completed Mar 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants