I created a module that adds a password protection to a site I'm testing craft on (I'm new to Craft and Yii, so please bear with me). In the front end there's a form where users enter a password and send it for validation.
I followed craft's recommendations for setting up the form: action attribute is empty, and there is a hidden field with the controller's route. The issue is that when there are validation errors, the page is reloaded (which is expected), but I cannot, or don't know how to, access the model nor its errors.
My controller has a function that is called when there's a validation error, and works like this:
Form action:
<input type="hidden" name="action" value="password-global/default/knock-knock">
DefaultController.php:
public function actionKnockKnock(
// control var
$validated = false;
// creates model instance
$model = new PasswordGlobalModel();
// gets form's posted data
$params = Craft::$app->request->getBodyParams();
// passes form's data to model
$model->attributes = $params;
// verifies data validity
if ( $model->validate() ):
$validated = true;
// some other logic
endif;
// ready to send response
if ($validated):
// redirection stuff
else:
Craft::$app->urlManager->setRouteParams(['myModel' => $model], true);
return null;
endif;
)
If I do a print_r
of $model before doing the setRouteParams(..)
part, I see the data model object as I expected... beginning like this:
abc\passwordglobal\models\PasswordGlobalModel Object
(
[theDate] =>
[theGreeting] =>
[action] => password-global/default/knock-knock
[theCurrentPage] => /contact
[_errors:yii\base\Model:private] => Array
(
[theGreeting] => Array
(
[0] => The password cannot be validated.
)
)
...
)
// In the reloaded form I have:
craft.app.request.getParam('myModel') // returns null
craft.app.request.getBodyParams() // returns array of data entered and submitted in the form's fields
The answer to this question helped me clarify things, but the proposed solution doesn't work for me.
Any suggestions on how to get the model/or its errors are greatly appreciated. Thank you!
EDIT 1, THE PROBLEM:
I did several changes, and now things are working. The issue was that my module had a form template that was rendered (using renderTemplage
) when a twig extension function was called from within the front end. I assume that doing it this way was preventing the rendered form from reading the model passed with setRouteParams
in the controller.
If I include the form as a front end template, then I have full access to the model.
I'm marking @August Miller's solution as the correct one, because it is the best and most generous overview of how Craft modules work. Thank you!