2

I'm using a module to add two actions to a form. When submitting the form I get this error. I have used pluginfactory to build this module. I am very new to modules/plugins, so if anyone knows more about this that would be very helpfull. Thanks in advance!

action used in form:

save-user-and-send-mail-module/default/do-something

the module:

<?php
/**
 * save user and send mail module for Craft CMS 3.x
 *
 * sdfsdf
 *
 * @link      https://arnemichiels.be/
 * @copyright Copyright (c) 2022 arne michiels
 */

namespace modules\saveuserandsendmailmodule;

use modules\saveuserandsendmailmodule\assetbundles\saveuserandsendmailmodule\SaveUserAndSendMailModuleAsset;

use Craft;
use craft\events\RegisterTemplateRootsEvent;
use craft\events\TemplateEvent;
use craft\i18n\PhpMessageSource;
use craft\web\View;
use craft\web\UrlManager;
use craft\events\RegisterUrlRulesEvent;

use yii\base\Event;
use yii\base\InvalidConfigException;
use yii\base\Module;

/**
 * Craft plugins are very much like little applications in and of themselves. We’ve made
 * it as simple as we can, but the training wheels are off. A little prior knowledge is
 * going to be required to write a plugin.
 *
 * For the purposes of the plugin docs, we’re going to assume that you know PHP and SQL,
 * as well as some semi-advanced concepts like object-oriented programming and PHP namespaces.
 *
 * https://craftcms.com/docs/plugins/introduction
 *
 * @author    arne michiels
 * @package   SaveUserAndSendMailModule
 * @since     1
 *
 */
class SaveUserAndSendMailModule extends Module
{
    // Static Properties
    // =========================================================================

    /**
     * Static property that is an instance of this module class so that it can be accessed via
     * SaveUserAndSendMailModule::$instance
     *
     * @var SaveUserAndSendMailModule
     */
    public static $instance;

    // Public Methods
    // =========================================================================

    /**
     * @inheritdoc
     */
    public function __construct($id, $parent = null, array $config = [])
    {
        Craft::setAlias('@modules/saveuserandsendmailmodule', $this->getBasePath());
        $this->controllerNamespace = 'modules\saveuserandsendmailmodule\controllers';

        // Translation category
        $i18n = Craft::$app->getI18n();
        /** @noinspection UnSafeIsSetOverArrayInspection */
        if (!isset($i18n->translations[$id]) && !isset($i18n->translations[$id.'*'])) {
            $i18n->translations[$id] = [
                'class' => PhpMessageSource::class,
                'sourceLanguage' => 'en-US',
                'basePath' => '@modules/saveuserandsendmailmodule/translations',
                'forceTranslation' => true,
                'allowOverrides' => true,
            ];
        }

        // Base template directory
        Event::on(View::class, View::EVENT_REGISTER_CP_TEMPLATE_ROOTS, function (RegisterTemplateRootsEvent $e) {
            if (is_dir($baseDir = $this->getBasePath().DIRECTORY_SEPARATOR.'templates')) {
                $e->roots[$this->id] = $baseDir;
            }
        });

        // Set this as the global instance of this module class
        static::setInstance($this);

        parent::__construct($id, $parent, $config);
    }

    /**
     * Set our $instance static property to this class so that it can be accessed via
     * SaveUserAndSendMailModule::$instance
     *
     * Called after the module class is instantiated; do any one-time initialization
     * here such as hooks and events.
     *
     * If you have a '/vendor/autoload.php' file, it will be loaded for you automatically;
     * you do not need to load it in your init() method.
     *
     */
    public function init()
    {
        parent::init();
        self::$instance = $this;

        // Load our AssetBundle
        if (Craft::$app->getRequest()->getIsCpRequest()) {
            Event::on(
                View::class,
                View::EVENT_BEFORE_RENDER_TEMPLATE,
                function (TemplateEvent $event) {
                    try {
                        Craft::$app->getView()->registerAssetBundle(SaveUserAndSendMailModuleAsset::class);
                    } catch (InvalidConfigException $e) {
                        Craft::error(
                            'Error registering AssetBundle - '.$e->getMessage(),
                            __METHOD__
                        );
                    }
                }
            );
        }

        // Register our site routes
        Event::on(
            UrlManager::class,
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
            function (RegisterUrlRulesEvent $event) {
                $event->rules['siteActionTrigger1'] = 'save-user-and-send-mail-module/default';
            }
        );

        // Register our CP routes
        Event::on(
            UrlManager::class,
            UrlManager::EVENT_REGISTER_CP_URL_RULES,
            function (RegisterUrlRulesEvent $event) {
                $event->rules['cpActionTrigger1'] = 'save-user-and-send-mail-module/default/do-something';
            }
        );

/**
 * Logging in Craft involves using one of the following methods:
 *
 * Craft::trace(): record a message to trace how a piece of code runs. This is mainly for development use.
 * Craft::info(): record a message that conveys some useful information.
 * Craft::warning(): record a warning message that indicates something unexpected has happened.
 * Craft::error(): record a fatal error that should be investigated as soon as possible.
 *
 * Unless `devMode` is on, only Craft::warning() & Craft::error() will log to `craft/storage/logs/web.log`
 *
 * It's recommended that you pass in the magic constant `__METHOD__` as the second parameter, which sets
 * the category to the method (prefixed with the fully qualified class name) where the constant appears.
 *
 * To enable the Yii debug toolbar, go to your user account in the AdminCP and check the
 * [] Show the debug toolbar on the front end & [] Show the debug toolbar on the Control Panel
 *
 * http://www.yiiframework.com/doc-2.0/guide-runtime-logging.html
 */
        Craft::info(
            Craft::t(
                'save-user-and-send-mail-module',
                '{name} module loaded',
                ['name' => 'save user and send mail']
            ),
            __METHOD__
        );
    }

    // Protected Methods
    // =========================================================================
}

error: enter image description here

controller:

class DefaultController extends Controller
{

    // Protected Properties
    // =========================================================================

    /**
     * @var    bool|array Allows anonymous access to this controller's actions.
     *         The actions must be in 'kebab-case'
     * @access protected
     */
    protected $allowAnonymous = ['index', 'do-something'];

    // Public Methods
    // =========================================================================

    /**
     * Handle a request going to our module's index action URL,
     * e.g.: actions/save-user-and-send-mail-module/default
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $result = 'Welcome to the DefaultController actionIndex() method';

        return $result;
    }

    /**
     * Handle a request going to our module's actionDoSomething URL,
     * e.g.: actions/save-user-and-send-mail-module/default/do-something
     *
     * @return mixed
     */
    public function actionDoSomething()
    {
        $result = 'Welcome to the DefaultController actionDoSomething() method';
        // Save the entry
        craft()->runController('users/save-user');

        // Send the notification
        craft()->runController('contact-form/send');

        return $result;
    }
}

1 Answer 1

9

Your module was created for Craft 3, but you're using Craft 4. Make sure to follow the upgrade guide and the plugin update guide if you're updating a site with custom modules to Craft 4.

You're seeing this error because Craft 4 added type declarations to most classes and methods. Custom classes that extend core classes need to be adjusted accordingly. In this case, you're extending craft\web\Controller, so your $allowAnonymous property declaration must match the declaration of the same property in the base class.

Adjust the declaration like this to get rid of this error:

protected array|bool|int $allowAnonymous = ['index', 'do-something'];

Note that pluginfactory.io is being discontinued and will be shut down by the end of the year. If you're just starting out, I would also avoid using power user tools like this one. You're just including tons of code in your project that you don't understand (as you have noticed) and therefore are not able to maintain properly. Better to start from scratch with the module guide and make sure to understand everything you're adding to your project completely.

1
  • 1
    Yup, this worked perfectly thanks a lot !
    – aren
    Commented Aug 8, 2022 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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