craftcms/contact-form

Defining rules for making additional fields required

dgsiegel opened this issue · 1 comments

Description

I am trying to make some additional fields required. Before contact-form 2.3.0 I defined the field in the form:

<div class="entry">
  {% set error = message.getErrors("message.city") ?? null %}
  <label for="from-city" class="form-label">{{ "City"|t }}</label>
  <input type="text" class="form-control{{ error ? " is-invalid"}}" id="from-city" name="message[City]" value="{{ message.message["City"] ?? '' }}">
</div>

Then in a custom plugin, I checked the value manually and reported back an error:

Event::on(Submission::class, Submission::EVENT_AFTER_VALIDATE, function(Event $e) {
  $submission = $e->sender;
    
  if (empty($submission->message["City"])) {
    $submission->addError("message.city", "The field City can't be empty.");
  }
}); 

With contact-form 2.3.0 one can now overwrite/add new rules via Submission::EVENT_DEFINE_RULES, however that only seems to be working for the existing fields fromName, fromEmail, subject, $message, attachment. If I try to add the above field like this:

Event::on(
  Submission::class,
  Submission::EVENT_DEFINE_RULES,
  function(DefineRulesEvent $event) {
    $event->rules[] = [["fromName", "message[City]"], "required"];
  }   
);   

I'll get an Getting unknown property: craft\contactform\models\Submission::message[City] error.

Additional info

  • Craft version: latest
  • PHP version: 8.0