craftcms / contact-form

Add a simple contact form to your Craft CMS site.
https://plugins.craftcms.com/contact-form
MIT License
293 stars 93 forks source link

Cannot use Yii file validator on a single file attachment field #254

Closed nstCactus closed 6 months ago

nstCactus commented 8 months ago

When using the Yii file validator on a single file attachment field, the validator always returns an error indicating that no file was uploaded.

Steps to reproduce

  1. Add a contact form with a single file attachment field:
<input type="file" name="attachment" />
  1. In a module, add a file validation rule on the attachment field:
Event::on(Submission::class, Submission::EVENT_DEFINE_RULES, static function(DefineRulesEvent $event): void {
    $event->rules[] = [ 'attachment', 'file', 'maxSize' => 2 * 1024 * 1024 ];
});
  1. Submit the form with a file

Expected outcome

The form should be successfully validated and the message sent.

Actuel outcome

There is a validation issue on the attachment field with the following message: Please upload a file.

Environment

Analysis

In this line, the $submission->attachment property is set to an array. The Yii file validator receives this array in its validateValue($value) method. This method checks that its $value parameter is an instance of \yii\web\UploadedFile which fails because it's actually an array.

i-just commented 6 months ago

Hi, Thanks for reporting and PRs! I raised a single one based on yours.

Once approved and released, you’ll be able to use the following for a form which allows a single attachment (<input type="file" name="attachment">):

Event::on(
    Submission::class,
    Submission::EVENT_DEFINE_RULES,
    function (DefineRulesEvent $event) {
        $event->rules[] = [ 'attachment', 'file', 'maxSize' => 1024];
    }
);

and this for a form which allows multiple attachments(<input type="file" name="attachment[]" multiple>):

Event::on(
    Submission::class,
    Submission::EVENT_DEFINE_RULES,
    function (DefineRulesEvent $event) {
        $event->rules[] = [ 'attachment', 'file', 'maxSize' => 1024, 'maxFiles' => 2];
    }
);
brandonkelly commented 6 months ago

Contact Form 2.5.3 (Craft 3) and 3.1.0 (Craft 4 and 5) have been released with that change 🎉