Structure of a form validation class - php

I want to make a class in OOP PHP to validate forms. However, I've having trouble structuring this.
Initially I thought of creating individual functions for each type of validation (check length of submitted data, check whether it's a number or not, etc), then another function to check whether data passed the validation tests and pass errors into an array.
I'm getting stuck though as my code is becoming very long and difficult to manage- I'm pretty new, so how would you approach this problem?

As i was reading through your post, a question came into my mind about what you write:
Why, instead of validating a form, dont you validte your model's objects?
I mean, in an OOP way of looking things your model´s object (or domain objects) are the ones who knows what data is valid or not for each of their attributes.
Not doint that, and pushing that logic into the UI makes your design fragile, UI dependant and harder to maintain. If you add a new attribute to one of your model's object, you'll have to modify the form validator as well.
If you go with Objects Validation, the idea is that an object cannot be created in an invalid state. If you try to modify it with invalid data, an exception will be thrown.
This makes easy to work with forms. The only think you have to do is populate your objects and watch for exceptions thrown in that process.
This is only an idea to get you started and see another way of solving this problem.
Regarding your question about Forms Validation, as the other guys said, it is always better not to reinvent the wheel and go for an existing, proven, validation framework.
However, if you are curious about it, here is one of the many ways you can do it:
Let's go through the things you need: you are talking about a form that needs to be validated with one or more validation functions. Then you talk about a function that tells you whether the form passed the validation or not, and as a result you got the list of errors found during the validation phase.
As you talk about OOP, the way to go is to give each concept or idea of your problem domain (the domain of form validation) entity via a class that represents it that model the behavior they have.
So, it is natural to think about a FormValidator class with a list of ValidationRule instances, where each one colaborates in the validation process. This validation process is done by calling the validate function of the FormValidator. Also, each ValidationRule will give, as result of calling it´s own validate method an instance of the ValidationRuleResult class, that tells whether the validation was successful or not, along with an error message and additional data (if needed) about the validation. Once all the validation rules were evaluated, the validate method of the FormValidator class will return an instance of ValidationResult class, that summarizes all the validation results of the rules evaluated providing the list of errors found.
To get this down to earth, here is the sample model we're talking about:
A sample implementation
Disclaimer: please bear in mind that, as any design, it may contains flaws. The following is intended to help you to solve your problem, not to be a complete solution.
class FormValidator {
private $_validationRules;
function __construct() {
$this->_validationRules = array();
}
// Registers a new validation rule
function addRule($aValidationRule) { $this->validationRules[] = $aValidationRule; }
// Validates $aForm, evaluating each of the $_validationRules defined
function validate($aForm) {
$aValidationResult = new ValidationResult();
foreach($this->_validationRules as $aValidationRule) {
$aValidationRuleResult = $aValidationRule->validate($aForm);
$aValidationResult->addResult($aValidationRuleResult);
}
return $aValidationResult;
}
}
abstract class ValidationRule {
private $_fieldName;
// The form's field name to be validated
function __construct($aFieldName) {
$this->_fieldName = $aFieldName;
}
function fieldName() { return $this->_fieldName; }
// Returns an instance of ValidationResult describing the result of evaluating the ValidationRule in $aForm.
abstract public function validate($aForm);
}
class ValidationResult {
private $_validationRuleResults;
function __construct() {
$this->_validationRuleResults = array();
}
// Registers a validation rule result
function addResult($aValidationRuleResult) {
$this->_validationRuleResults[] = $aValidationRuleResult;
}
// Returns the list of the error messages of the validation rule results that did't passed
function errorsFound() {
$errors = array();
foreach($this->validationRuleResults as $aValidationResult) {
if ($aValidationResult->passed()) continue;
$errors[] = $aValidationResult->errorMessage();
}
return $errors;
}
// Tells whether all the validation rule results passed or not
function validationPassed() {
foreach($this->validationRuleResults as $validationResult) {
if ($validationResult->passed() == false) return false;
}
return true;
}
}
class ValidationRuleResult {
private $_passed, $_error_message;
function __construct($passed) {
$this->_passed = $passed;
$this->_error_message = '';
}
// Tells whether the form passed this validation rule or not
public function passed() { return $this->_passed; }
public function
// The error message should be empty if passed to avoid confusion
public function errorMessage { return $this->passed() ? '' : $this->_error_message; }
public function setErrorMessage($anErrorMessage) { $this->_error_message = $anErrorMessage; }
}
You can create a validation rule this way:
class NotEmptyValidationRule extends ValidationRule {
public function validate($aForm) {
$fieldName = $this->fieldName();
$fieldValue = $aForm[$fieldName];
$passed = !empty($fieldValue);
$result = new ValidationRuleResult($passed);
if (!$passed) {
$result->setErrorMessage("$fieldName cannot be empty");
}
return $result;
}
}
Some things to note:
Im assuming that $aForm is an associative array of field name / value
You can note that if a validation rule passes, the result is not used (as the ValidationResult class works only on those results that didn't pass). Remember that this is a sample only for the purpose of helping you, is not a complete solution.
Usage
$rule = new NotEmptyValidationRule('name');
$validator = new FormValidator();
$validator->addRule($rule);
$aForm = $__POST['myForm'];
$validationResult = $validator->validate($aForm);
if ($validationResult->validationPassed()) {
$errorsFound = $validationResult->errorsFound();
// do something with the $errorMessage
$errorMessage = array_join('<br/>', $errorsFound);
}

Related

Where object should be validated?

My problem is that I don't know, witch solution for the validation of input is better and if there is another, better solution. Well, where object should be validated? On the one hand, the object should always be correct. On the other hand, if the user specifies several incorrect data, it's a more elegant solution to notify him of all errors, not just one (first occured).
// Solution 1:
try {
$user = new User();
$user->setFirstname($_POST['firstname']);
$user->setSecondname($_POST['secondname']);
$user->setLastname($_POST['lastname']);
$user->hasLeftHand($_POST['has-left-hand']);
$user->hasRightHand($_POST['has-right-hand']);
$user->setHandedness($_POST['handedness']);
$user->save($pdo);
} catch (Exception $e) {
echo $e->getMessage();
}
// Solution 2:
$user = new User();
$user->setFirstname($_POST['firstname']);
$user->setSecondname($_POST['secondname']);
$user->setLastname($_POST['lastname']);
$user->hasLeftHand($_POST['has-left-hand']);
$user->hasRightHand($_POST['has-right-hand']);
$user->setHandedness($_POST['handedness']);
$errors = $user->validate();
if (empty($errors)) {
$user->save($pdo);
} else {
echo 'Some errors occured: ' . implode(', ', $errors);
}
// Solution 3:
try {
$user = new User();
$user->setFirstname($_POST['firstname']);
$user->setSecondname($_POST['secondname']);
$user->setLastname($_POST['lastname']);
$user->hasLeftHand($_POST['has-left-hand']);
$user->hasRightHand($_POST['has-right-hand']);
$user->setHandedness($_POST['handedness']);
$user->save($pdo);
} catch (Exception $e) {
$errors = $user->validate();
echo 'Some errors occured: ' . implode(', ', $errors);
}
In solution 1 each set method validates the input. Therefore, the object is always correct. The save method only saves the object in the database. On the other hand, if all the data is incorrect, it will be displayed only the first error.
In solution 2 we allow that object can not be correct between set calls, but to the database can be saved only valid object. set methods do not validate the input. validate method validates the object as a whole, and returns a list of all errors found. save method looks like this:
public function save(PDO $pdo)
{
if(! empty($this->validate())) {
throw new Exception('Invalid state');
}
// Store in database
}
In this solution is easier to validate the object. Becouse, how should work code below in solution 1?
$user->hasLeftHand(true);
$user->hasRightHand(false);
$user->setHandedness('right');
Or this code:
$user->setHandedness('right');
$user->hasLeftHand(true);
$user->hasRightHand(false);
Solution 3 is a copy of solution 2. Code of User class is the same. Changes only its use - try-catch block. In my opinion, this code looks more clearly.
Validation of input should be separated from validating the correctness of a domain object itself. Many frameworks use Form classes for this. Maybe have a look at how it's done in:
Symfony
Zend Framework (Form InputFilters)
In short, the form will validate the input, and will populate a bound object in case the data is valid.
disclaimer: this question is opinion based, and there is no 1 correct answer... but I'll true to recap what we discussed in comments and how I think most people solve it.
separate input validation from the model
<?php
// class for input validation
class UserValidator
{
public function validate(array $data)
{
$errors = array();
if (isset($data['email'])) {
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'email not valid';
}
} else {
$errors['email'] = 'email is required';
}
}
}
// model class itself, does not implement extensive validation
class User
{
protected $email;
public function setEmail($email)
{
// only make sure we have a valid string, dont validate email again
if (!is_string($email) || !strlen($email)) throw new \InvalidArgumentException('invalid email given');
$this->email = $email;
return $this;
}
}
So this example separates the input validation so it is easy to provide user feedback when processing form data. The model itself only performs basic checks, and assumes the developer is smart enough to set sane data...
<?php
// where you process a form POST...
$validator = new UserValidator();
$errors = $validator->validate($_POST);
if (count($errors)) {
// provide feedback to your user, he gave us bogus data...
return $errors;
}
// if we are here, we passed validation and can assume our data is good
$user = new User();
$user->setEmail($_POST['email']);
This is a very simplified example, again you should check out how the major frameworks solve this problem, they've had many people thinking hard about this already...
And as the differences between Zend and Symfony underline: there is no golden hammer for this.

MVC Validation Advice

I'm currently validating input and returning errors in a "fat controller" as follows:
class SomeController
{
public function register()
{
// validate input
$username = isset($_POST['username']) && strlen($_POST['username']) <= 20 ? $_POST['username'] : null;
// proceed if validation passed
if (isset($username)) {
$user = $this->model->build('user');
if ($user->insert($username)) {
$_SESSION['success'] = 'User created!';
} else {
$_SESSION['error'] = 'Could not register user.';
}
} else {
$_SESSION['failed']['username'] = 'Your username cannot be greater than 20 characters.';
}
// load appropriate view here
}
}
class SomeModel
{
public function insert($username)
{
// sql for insertion
// ...
return $result;
}
}
While this works and is easy enough for me to implement, I understand that this is incorrect because the validation belongs in the model, which I'm attempting to correct using a "fat model" as follows:
class SomeController
{
public function register()
{
$user = $this->model->build('user');
$user->insert($_POST['username']);
// load appropriate view here
// ...
}
}
class SomeModel
{
public function insert($username)
{
// validate input
$error = false;
$username = trim($username) != '' && strlen($username) <= 20 ? $username : null;
// proceed if validation passed
if (isset($username)) {
// sql for insertion
// ...
$_SESSION['success'] = 'User created!';
} else {
// store error in session
$error = true;
$_SESSION['error']['username'] = 'Your username cannot be greater than 20 characters ';
}
return $error ? false : true;
}
}
The problem I see here is that the model is supposed to be portable, in that it should never need to change. But if the requirement for the length of $username changes, then obviously I'll have to alter my model.
I feel like this may be a really common question but I've yet to find a straight-forward answer. Without implementing any extra "layers", "mappers" or whatever other confusing terms are out there, how could the example pseudo-code provided be modified to correctly handle this transaction? (eg, validate input, return error if validation fails)?
Without implementing any extra "layers", "mappers" or whatever
You should consider the "model" to be a application layer rather than a single class. The term "layer" could be thought of as a simple way to reference the M slice of MVC sandwich. So to accomplish the flexibility you desire you will need to create it.
A number of clear seperations can be made. I would consider having three abstractions: services, data mappers and entities.
A service would be exposed to the controller and perform the service being requested.
// some controller
function register() {
$service = $this->getUserService();
$user = $service->register($_POST['first_name'], $_POST['last_name']);
if ($user instanceof \My\Entity\User) {
// set user in view
} else {
// redirect to error
}
}
So task one complete, the controller is now dumb to whatever happens within register, all it wants to know is how to resolve the appropriate result. If there is a user object, success, otherwise false something went wrong.
The service class itself would encapsulate the services being offered:
// class UserService.php
function register($firstname, $lastname) {
// validate arguments
if ($this->isValidUsername(....
$userMapper = $this->getUserMapper();
$user = new My\Entity\User();
$user->setFirstName($firstname);
$user->setLastName($lastname);
return $userMapper->save($user);
}
return false;
}
We handle the validation of the arguments and also create the new user, passing it to the data mapper which will perform the "actual save" abstracting the database operations.
// UserMapper
function save($user) {
// save $user to db
$sql = 'INSERT INTO ....
return true;
}
I'm not sure what you would consider to be an undesirable "layer" or "mapper". This is an interesting question, and my first though was that you could just include a configuration file that defined a constant for your username length. My second though was that you could have someModel extend a class or implement an interface, wherein you values would be set as properties or constants. I suspect that you have thought of these, and are avoiding them; that this is what you mean by avoiding "layers" and "mappers" It seems that you are being guided by these principals in this code:
Avoid "magic numbers"
KISS
Composition over inheritance
skinny controller/fat model
So, are you running php5.4+ ? Maybe define a trait which could be used in this and other models that defines the username length and other changeable values in the application. Or maybe that too is to much of a "layer"?

CodeIgniter form validation using session variables

How do I get the CodeIgniter form validation to validate the $_SESSION if there is no passed form data? I tried manually setting the $_REQUEST variable, but it doesn't seem to work.
i.e. I have a function search in the controller which validates the form input passed, and either returns you to the previous page with errors, or else moves you onto the next page. But I want this function to also work if you previously filled out this page, and the info is stored in the $_SESSION variable.
function search () {
$this->load->library("form_validation");
$this->form_validation->set_rules("flightID", "Flight Time", "required|callback_validFlightID");
$this->form_validation->set_rules("time", "Flight Time", "required|callback_validFlightTime");
$this->setRequest(array("flightID", "time"));
// adding session check allows for inter-view navigation
if ($this->form_validation->run()) {
// some application logic here
$this->load->view("seats", $data);
} else {
$this->logger->log($_REQUEST, "request");
// redirect back to index
$this->index();
}
}
function setRequest () {
// make sure none of the parameters are set in the request
foreach ($vars as $k) {
if (isset($_REQUEST[$k])) {
return;
}
}
foreach ($vars as $k) {
if (isset($_SESSION[$k])) {
$_REQUEST[$k] = $_SESSION[$k];
}
}
}
You can store the form post info in a session using the following codeigniter functions
$formdata = array(
'flightID' => $this->input->post('flightID'),
'time' => $this->input->post('time')
);
$this->session->set_userdata($formdata);
and the information can be retrieved with the following
$this->session->userdata('flightID')
$this->session->userdata('time')
form_validation works directly with $_POST, so use that instead of $_REQUEST.
What you're trying to do is setting Post values manually which is not natively
supported by CodeIgniter. So what we're doing first is extending the core.
Create a new file (MY_Input.php) and paste the following contents into it:
class MY_Input extends CI_Input{
function set_post($key, $value)
{
$_POST[$key] = $value;
}
}
That's a very basic implementation of your purpose but it's enough to test around. You might want to extend it to make it fit your needs (f.e. allowing the input of arrays).
So now. In your controller you can check if something has been posted by a user. If not you'll be just setting the post variable manually with your new method of the Input class.
class Some_Controller extends CI_Controller{
public function index()
{
// The user hasn't filled out a field?
if(!$this->input->post('a_key'))
{
// Let's set the postfield to the value of a session key
$this->input->set_post('a_key', $this->session->userdata('mystoredkey'));
}
}
}
After having set your postfield manually, it can be handled by the form validation library as it is meant to be.
That should be your way to go :)
You can really do some pretty things if you're not afraid of hacking the core. Many people are, don't be one of them!
Happy coding

Zend_Form_Element: add class if it contains errors

In my current application, I would like to color the select options red when they contain faulty information (aka not validated). When a form element contains one or more errors, it should have an error class (so I can style accordingly). I tried looping through the elements, and seeing if they validated, but this gets very ugly very quickly.
How would I get this done in a better way?
Thanks
Edit: This is my current workaround (and gets the job done, but dirtily)
$post = $request->getPost();
foreach ($contactForm->getElements() as $element) {
if (!$element->isValid($post[$element->getName()])) {
$element->setAttrib('class', 'error');
}
}
Here are a couple of thoughts...
Instead of calling isValid on every form element, you can validate your whole form with isValid, and then loop over your elements as you are in your question, but instead use if ($element->hasErrors()) to determine if you need to add the error class to the element.
You may want to extend from Zend_Form and add a helper method to your new Form class that does this for you. For example, add a method called highlightErrorElements() or something like that and if you have an unsuccessful call to $form->isValid(), you can then simply call $form->highlightErrorElements() which will loop over each form element and see if it has errors and apply the style if necessary.
Example:
<?php
class Application_Form_Base extends Zend_Form
{
public function __construct()
{
// this is where i normally set up my decorators for the form and elements
// additionally you can register prefix paths for custom validators, decorators, and elements
parent::__construct();
// parent::__construct must be called last because it calls $form->init()
// and anything after it is not executed
}
public function highlightErrorElements()
{
foreach($this->getElements() as $element) {
if($element->hasErrors()) {
$element->setAttrib('class', 'error');
}
}
}
}
Somewhere, in a controller...
$form = new Application_Form_Register(); // this extends Application_Form_Base
if ($form->isValid($this->getRequest()->getPost())) {
// add user etc
} else {
$form->highlightErrorElements();
// other error logic
}
$this->view->form = $form;

How to create modular MVC components in Zend Framework

I've been having problems created modular reusable components in my Zend Framework app. In this case I'm not referring to Zend Framework modules but rather the ability to have a reusable MVC widgety thing if you like. The problems I'm having may be very particular to my implementation, but I'm completely happy to throw it out and start again if someone can point me in the right direction. Anyway, specifics and code will hopefully explain things better and even if what I'm doing is not the best way it should show what I'm trying to achieve:
A simple example is a Mailing List sign up form. I want to include this on several pages of the site which use different Controllers and this presents a few problems in how to process the data and return relevant messages. I don't want to do either of the following as they really smell:
Create a base controller with the form processing in and extend (Bad)
Duplicate form processing code in relevant controllers (Even worse!)
The clean way to go feels to me to create a new Controller to process the mailing list form data, use a View Helper to easily output the form and relevant markup into the desired pages and then redirect back to the page where signup occurred once the form has been processed. However, I'd like to use the form validation provided by Zend_Form, which means I'd need to pass the form object back to the view helper somehow if validation fails but in the same request. I'm currently doing this by setting it as a variable on the view and then forwarding back to the previous page rather than redirecting, which is ok(ish). If validation is ok then I'd prefer to use a redirect back to the original page. I'm having trouble doing this though as I'd like to pass messages back to the component about the state of signup. Normally I'd use the FlashMessenger Action Helper, I could namespace it in this case so messages didn't clash with other page data, but I can't access it from within a View Helper. So currently I'm forwarding in this case too. I'd much prefer a redirect to prevent form resubmissions if a user refreshes the page and to keep the URL clean. I realise I essentially want to have a mini MVC dispatch process within a page and I think that's what the action stack is for? I really don't know much about this though and any pointers would be greatly appreciated. Here's my current code:
Controller:
<?php
class MailingListController extends Zend_Controller_Action {
public function insertAction() {
$request = $this->getRequest();
$returnTo = $request->getParam('return_to');
if(!$request->isPost() || (!isset($returnTo) || empty($returnTo))) {
$this->_redirect('/');
}
$mailingList = new Model_MailingList();
$form = new Form_MailingList();
$returnTo = explode('/', $returnTo);
if($form->isValid($_POST)) {
$emailAddress = $form->getValue('email_address');
$mailingList->addEmailAddress($emailAddress);
$this->view->mailingListMessages = $mailingList->getMessages();
$this->view->mailingListForm = "";
}
else {
$this->view->mailingListForm = $form;
}
$this->_forward($returnTo[2], $returnTo[1], $returnTo[0]);
}
}
return_to is a string containing the current URI (module/controller/action), which is generated in the View Helper. I'd prefer to redirect inside the $form->isValid($_POST) block.
View Helper:
<?php
class Zend_View_Helper_MailingList extends Zend_View_Helper_Abstract {
public function mailingList($form, $messages = "") {
if(!isset($form)) {
$request = Zend_Controller_Front::getInstance()->getRequest();
$currentPage = $request->getModuleName() . '/' . $request->getControllerName() . '/' . $request->getActionName();
$form = new Form_MailingList();
$form->setAction('/mailing-list/insert');
$form->setCurrentPage($currentPage);
}
$html = '<div class="mailingList"><h2>Join Our Mailing List</h2>' . $form;
$html .= $messages;
$html .= '</div>';
return $html;
}
}
Getting an instance of the Front Controller in the View Helper isn't ideal but I'd prefer to encapsulate as much as possible.
If I have a form object where validation has failed I can pass it back into the helper to output with error messages. If I have some messages to render I can also pass them into the helper.
In my view scripts I'm using the helper like so:
<?=$this->mailingList($this->mailingListForm, $this->mailingListMessages);?>
If neither mailingListForm or mailingListMessages has been set on the view by MailingListController, it will output a new form with no messages.
Any help is greatly appreciated!
Using ajax seems to be an optimal way. View Action Helper is used only for the first load of the mailing form.
Controller
class MailingListController extends Zend_Controller_Action {
public function insertAction() {
$request = $this->getRequest();
$form = new Form_MailingList();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
$mailingList = new Model_MailingList();
$emailAddress = $form->getValue('email_address');
$mailingList->addEmailAddress($emailAddress);
$form = $mailingList->getMessages();
}
}
$this->view->form = $form;
}
}
view script insert.phtml
<?php echo $this->form; ?>
Form class
class Form_MailingList extends Zend_Form {
public function init() {
//among other things
$this->setAttrib('id', 'mailing-list-form');
$this->setAction('/mailing-list/insert');
}
}
View Helper
class Zend_View_Helper_MailingList extends Zend_View_Helper_Abstract {
public function mailingList() {
$this->view->headScript()->appendFile('/js/mailing-list.js');
return '<div id="mailing-list-wrap">' . $this->view->action('insert', 'mailing-list') . '</div>';
}
}
JS file mailing-list.js
$(document).ready(function() {
$('#mailing-list-form').submit(function() {
var formAction = $(this).attr('action');
var formData = $(this).serialize();
$.post(formAction, formData, function(data) {
//response going in form's parent container
$(this).parent().html(data);
});
return false;
});
});
I think the way you've done it is pretty close to what I would do. If you set aside the requirement of wanting to display the Zend_Form error messages in the page, then what you do instead is:
The view helper just displays the form (it doesn't need to take the form object or messages as parameters)
The form submits to your other controller as it does now
The mailing list controller redirects (instead of forwarding) back to the return URL on success
The mailing list controller redisplays the form on its own, along with errors on failure
This makes everything much simpler, the only issue is that if there are any validation errors then the user loses their context and gets a plain old page with the form on instead of where they were. You can then address this (either now or at a later date) by changing the form to submit via. Ajax instead, and rendering the errors via. JS. But this would be a fair amount of work.
OK, I've come up with a solution that I feel happier about and solves some of the problems I was facing. Hopefully, this might help someone out who's facing similar issues. The only downside now is that I'm referencing the Model inside the View Helper. Not loose coupling I know but I've seen this done several times before and it's even recommended in the ZF docs as a way to avoid using the 'action' view helper (which will create a new MVC dispatch loop). On the whole, I think the DRYness and encapsulation is worth it, there's probably some other suitable lingo too.
In order to be able to use a redirect back from my MailingListController but maintain the messages from my model and any form validation errors I need to store them in the session. For messages I'd normally use the FlashMessenger action helper, but as getting hold of this in a View Helper is not best practice, it won't handle my form errors and all it's really doing is saving stuff to the session anyway it's unnecessary. I can implement my own session storage in the Model_MailingList, which I can also use for the form errors. I can then repopulate the form with the errors after the redirect and print out any relevant messages. Anyway, here's the code:
Controller:
<?php
class MailingListController extends Zend_Controller_Action {
public function insertAction() {
$request = $this->getRequest();
$returnTo = $request->getParam('return_to');
if(!$request->isPost() || (!isset($returnTo) || empty($returnTo))) {
$this->_redirect('/');
}
$mailingList = new Model_MailingList();
$form = new Form_MailingList();
if($form->isValid($_POST)) {
$emailAddress = $form->getValue('email_address');
$mailingList->addEmailAddress($emailAddress);
}
else {
$mailingList->setFormErrors($form->getMessages());
}
$redirect = rtrim($request->getBaseUrl(), '/') . $returnTo;
$this->_redirect($redirect);
}
}
I've added a method to my Model_MailingList class; setFormErrors($errors) that I pass the error messages from the form if it fails validation. This saves the error array to the session.
I normally use a base model class that has addMessage and getMessages methods. These just access a protected array of messages. In my Model_MailingList I override these methods to store the messages in the session instead. In the addEmailAddress($emailAddress) method I'm already calling addMessage to say whether inserting the email address to the db has been successful.
Model:
<?php
class Model_MailingList extends Thinkjam_Model_DbAbstract {
private $_session;
public function __construct() {
$this->_session = new Zend_Session_Namespace(__CLASS__);
}
public function setFormErrors($errors) {
$this->_session->formErrors = $errors;
}
public function getFormErrors() {
$errors = array();
if(isset($this->_session->formErrors)) {
$errors = $this->_session->formErrors;
unset($this->_session->formErrors);
}
return $errors;
}
// override addMessage and getMessages
protected function addMessage($message) {
if(!isset($this->_session->messages)) {
$this->_session->messages = array();
}
$this->_session->messages[] = $message;
}
public function getMessages() {
if(isset($this->_session->messages)) {
$this->_messages = $this->_session->messages;
unset($this->_session->messages);
}
return $this->_messages;
}
…
public function addEmailAddress($emailAddress) {
...
// I call this if db insert was successful:
$this->addMessage("Thank you. You have been successfully added to the mailing list.")
}
}
I now don't need to pass any params to the view helper as it can query it's state from the Model directly. $this->view->messenger is just another view helper that converts an array to an unordered list.
View Helper:
<?php
class Zend_View_Helper_MailingList extends Zend_View_Helper_Abstract {
private $_mailingList;
public function MailingList() {
$this->_mailingList = new Model_MailingList();
return $this;
}
public function getForm() {
$request = Zend_Controller_Front::getInstance()->getRequest();
$currentPage = '/' . $request->getModuleName() . '/' . $request->getControllerName() . '/' . $request->getActionName();
$form = new Form_MailingList();
$form->setAction('/mailing-list/insert');
$form->setCurrentPage($currentPage);
$form->setErrors($this->_mailingList->getFormErrors());
$html = '<div class="mailingList"><h2>Join Our Mailing List</h2>' . $form;
$html .= $this->view->messenger($this->_mailingList->getMessages());
$html .= '</div>';
return $html;
}
}
Then in the Form_MailingList class I just need to add an additional method to repopulate the error messages. Although getMessages() is a method of Zend_Form there doesn't appear to be any corresponding setMessages(). You can do this on a Zend_Form_Element however, so I've added the following function to the Form_MailingList class:
Form:
<?php
class Form_MailingList extends Thinkjam_Form_Abstract {
...
public function setErrors(array $errors) {
foreach($errors as $key => $value) {
$this->getElement($key)->setErrors($value);
}
}
}
I can now add a signup form on any page of my site using the MailingList view helper:
<?=$this->MailingList()->getForm();?>
I realise a lot of the problems I was facing was down to a very specific set of circumstances, but hopefully this can help some other people out in some way!
Cheers,
Alex

Categories