3

When using the Pixel & Tonic contact form (https://github.com/pixelandtonic/ContactForm) how do you make the fromName field required?

When using the form as seen on github, only the message and email field are required.

Thank you!

0

Currently, there isn't a native way.

You could write some JS that does client-side validation, fork the repo add it yourself or if you're looking for a more complete form-building solution, hit up these guys.

| improve this answer | |
2

It's relatively simple to tweak the Contact Form plugin to change the required fields. If you open models/ContactFormModel.php (in the plugin's folder), you can add 'required' => true, to the fromName attribute definition:

'fromName'   => array(AttributeType::String, 'required' => true, 'label' => 'Your Name'),

I tried this out, and it seemed to work as expected.

| improve this answer | |
  • 1
    Just be aware that those changes will be lost if you ever update the plugin. – Lindsey D Nov 10 '14 at 21:58
  • Yep, good point - this change does effectively amount to forking the plugin. You could potentially still update the plugin via a git merge, but certainly the process will be more complicated, and you'll need to remember to do it this way rather than overwriting it with a newer version. – Nick F Nov 13 '14 at 19:13
  • Not good this one. If you actively update your CMS which you should, then this is not a solution. – Laurence Cope May 21 '18 at 8:37
2

You could also hand this over to HTML since it supports form validation as of version 5. Depends on your browser support requirements though. This is what “Can i use” says.

| improve this answer | |
  • 1
    Client-side form validation is generally best thought of as an enhancement rather than a replacement for server-side validation. You can never know for sure that user input has been validated on the client side, so you can't rely on it. – Nick F Nov 13 '14 at 19:09
1

Sprout Forms works great for making fields required. It nicely places the error info on the page (if you have the error tags in place) without losing the form data. Slick!

| improve this answer | |
1

Unfortunately, the Craft devs have not made this as easy as it should be. Luckily, we can utilize that it's built on Yii2.

The following solution makes fromNamerequired, and are compatible with Contact Form Extensions.


Make a new folder inside modules and call it contact_form. Create the following file structure:

modules\
  contact_form\
    controllers\
      SendController.php
    models\
      Submission.php
    Module.php

And enter the following into the files:


SendController.php (This is almost an exact copy of craft\contactform\controllers, but we're pointing it to our own Submission model)

namespace modules\contact_form\controllers;

use Craft;    
use modules\contact_form\models\Submission;
use craft\contactform\Plugin;
use craft\web\UploadedFile;
use yii\web\Response;

class SendController extends \craft\contactform\controllers\SendController
{

    public function actionIndex()
    {
        $this->requirePostRequest();
        $request = Craft::$app->getRequest();
        $plugin = Plugin::getInstance();
        $settings = $plugin->getSettings();

        $submission = new Submission();
        $submission->fromEmail = $request->getBodyParam('fromEmail');
        $submission->fromName = $request->getBodyParam('fromName');
        $submission->subject = $request->getBodyParam('subject');

        $message = $request->getBodyParam('message');
        if (is_array($message)) {
            $submission->message = array_filter($message, function($value) {
                return $value !== '';
            });
        } else {
            $submission->message = $message;
        }

        if ($settings->allowAttachments && isset($_FILES['attachment']) && isset($_FILES['attachment']['name'])) {
            if (is_array($_FILES['attachment']['name'])) {
                $submission->attachment = UploadedFile::getInstancesByName('attachment');
            } else {
                $submission->attachment = [UploadedFile::getInstanceByName('attachment')];
            }
        }

        if (!$plugin->getMailer()->send($submission)) {
            if ($request->getAcceptsJson()) {
                return $this->asJson(['errors' => $submission->getErrors()]);
            }

            Craft::$app->getSession()->setError(Craft::t('contact-form', 'There was a problem with your submission, please check the form and try again!'));
            Craft::$app->getUrlManager()->setRouteParams([
            'variables' => ['message' => $submission]
            ]);

            return null;
        }

        if ($request->getAcceptsJson()) {
            return $this->asJson(['success' => true]);
        }

        Craft::$app->getSession()->setNotice($settings->successFlashMessage);
        return $this->redirectToPostedUrl($submission);
    }
}

Submission.php

namespace modules\contact_form\models;

class Submission extends \craft\contactform\models\Submission
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['fromEmail', 'message', 'fromName'], 'required'],
        ];
    }
}

Module.php

class Module extends \yii\base\Module
{
    public function init()
    {
        $this->controllerNamespace = 'modules\\contact_form\\controllers';
        parent::init();
    }
}

config\app.php

Update to include your module:

return [
    'modules' => [
        ...
        'contact' => \modules\contact_form\Module::class
        ...
    ],
    ...
];

Your view And finally update your form code to use your new controller:

<input type="hidden" name="action" value="contact/send">
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.