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

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

Closed
nstCactus opened this issue Jan 18, 2024 · 2 comments
Closed

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

nstCactus opened this issue Jan 18, 2024 · 2 comments

Comments

@nstCactus
Copy link
Contributor

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

  • Craft version: 3.9.10
  • contact-form plugin version: 2.5.2

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
Copy link
Contributor

i-just commented Mar 7, 2024

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
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants