8

I've done quite a few Lithium tutorials (links below in case they help someone else, and also to show I've done my homework:) and I understand the most basic parts of creating models, views, controllers and using MVC to create a DB record based on form input.

However, I'm new to MVC for webapps and Lithium, and I'm not sure how I should write my code in more complicated situations. This is a general question, but two specific validation questions that I have are:

  • How should I validate date data submitted from the form?
  • How should I check that the two user email fields have the same value?

I would be very grateful for any help with these questions, and concrete examples like this will also really help me understand how to do good MVC coding in other situations as well!

Date entry - validating data split across multiple form inputs

For UI reasons, the sign up form asks users to enter their DOB in three fields:

<?=$this->form->field('birthday', array('type' => 'select', 'list' => array(/*...*/))); ?>
<?=$this->form->field('birthmonth', array('type' => 'select', 'list' => array(/*...*/))); ?>
<?=$this->form->field('birthyear', array('type' => 'select', 'list' => array(/*...*/))); ?>

What is the best way to validate this server-side? I think I should take advantage of the automagic validation, but I'm not sure of the best way do that for a set of variables that aren't really part of the Model. E.g.:

  • Should I post-process the $this->request->data in UsersController? E.g. modify $this->request->data inside UsersController before passing it to Users::create.
  • Should I pull the form fields out of $this->request->data and use a static call to Validator::isDate inside UsersController?
  • Is there a way to write a validation rule in the model for combinations of form variables that aren't part of the model?
  • should I override Users::create and do all the extra validation and post-processing there?

All of these seem like they could work, although some seem a little bit ugly and I don't know which ones could cause major problems for me in the future.

[EDIT: Closely related to this is the problem of combining the three form fields into a single field to be saved in the model]

Email entry - checking two form fields are identical, but only storing one

For common sense/common practice, the sign up form asks users to specify their email address twice:

<?=$this->form->field('email_address'); ?>
<?=$this->form->field('verify_email_address'); ?>

How can I write an automagic validation rule that checks these two form fields have the same value, but only saves email_address to the database?

This feels like it's pretty much the same question as the above one because the list of possible answers that I can think of is the same - so I'm submitting this as one question, but I'd really appreciate your help with both parts, as I think the solution to this one is going to be subtle and different and equally enlightening!

[EDIT: Closely related to this is the problem of not storing verify_email_address into my model and DB]

Some background reading on Lithium

I've read others, but these three tutorials got me to where I am with users and sign up forms now...

Some other StackOverflow questions on closely related topics (but not answering it and also not Lithium-specific)

  • One answer to this question suggests creating a separate controller (and model and...?) - it doesn't feel very "Lithium" to me, and I'm worried it could be fragile/easily buggy as well
  • This wonderful story convinced me I was right to be worried about putting it in the controller, but I'm not sure what a good solution would be
  • This one on views makes me think I should put it in the model somehow, but I don't know the best way to do this in Lithium (see my bulleted list under Date Entry above)
  • And this Scribd presentation asked the question I'm hoping to answer on the last page... whereupon it stopped without answering it!

NB: CakePHP-style answers are fine too. I don't know it, but it's similar and I'm sure I can translate from it if I need to!

Community
  • 1
  • 1
cfogelberg
  • 1,468
  • 19
  • 26
  • 1
    Summary from discussion with SofaCitizen (2012-04-01): The submitted data should be post-processed in the controller. This is because the model stores a date, not three separate fields which make up a date. Communicating validation information back to the view is a bit difficult, but one solution is to add a "DOB" field to the form after the 3 date entry fields. Setting this DOB fields display to none may still allow error messages for it (by proxy the other date fields) to be displayed. – cfogelberg Apr 01 '12 at 23:32
  • [Chat logs here](http://lithify.me/en/bot/logs/li3/2012-04-01) – cfogelberg Apr 04 '12 at 14:34

1 Answers1

4

I'd recommend doing this in the Model rather than the Controller - that way it happens no matter where you do the save from.

For the date field issue, in your model, override the save() method and handle converting the multiple fields in the data to one date field before calling parent::save to do the actual saving. Any advanced manipulation can happen there.

The technique described in your comment of using a hidden form field to get error messages to display sounds pretty good.

For comparing that two email fields are equal, I'd recommend defining a custom validator. You can do this in your bootstrap using Validator::add.

use lithium\util\Validator;
use InvalidArgumentException;

Validator::add('match', function($value, $format = null, array $options = array()) {
    $options += array(
        'against' => '',
        'values' => array()
    );
    extract($options);
    if (array_key_exists($against, $values)) {
        return $values[$against] == $value;
    }
    return false;
});

Then in your model:

public $validates = array(
    "email" => array(
        "match",
        "message" => "Please re-type your email address.",
        "against" => "email2"
    )
);

Edit: Per the comments, here's a way to do custom rule validation in a controller:

public function save() {
    $entity = MyModel::create($this->request->data);
    $rules = array(
        "email" => array(
            "match",
            "message" => "Please re-type your email address.",
            "against" => "email2"
        )
    );

    if (!$entity->validates($rules)) {
        return compact('entity');
    }

    // if your model defines a `$_schema` and sets `$_meta = array('locked' => true)`
    // then any fields not in the schema will not be saved to the db

    // here's another way using the `'whitelist'` param
    $blacklist = array('email2', 'some', 'other', 'fields');
    $whitelist = array_keys($entity->data());
    $whitelist = array_diff($whitelist, $blacklist);

    if ($entity->save(null, compact('whitelist'))) {
        $this->redirect(
            array("Controller::view", "args" => array($entity->_id)),
            array('exit' => true)
        );
    }

    return compact('entity');
}

An advantage of setting the data to the entity is that it will be automatically prefilled in your form if there's a validation error.

botero
  • 598
  • 2
  • 11
  • 23
rmarscher
  • 5,596
  • 2
  • 28
  • 30
  • thanks for the reply and your suggestion of putting it in the model to make it available everywhere sounds smart. Because these three fields are just used in the form submission now though and not other situations I will add a "process form data" method to the model and pass the return value from that to the save function. Your validator idea also seems really smart, I hadn't thought of it like that. One thing I don't understand is how/where `$options['values']` is populated with the submitted form fields. Does this happen automagically? – cfogelberg Apr 04 '12 at 15:01
  • `$options['values']` is automagic. Look at [Model::validates](http://lithify.me/docs/lithium/data/Model::validates()). `$validator::check($entity->data(), $rules, $options)` is called and `$entity->data()` is passed eventually through to `$options['values']`. It's a little convoluted how that happens, but in `Validator::check()` there's `$rule += $options + compact('values');` where `$values` is the `$entity->data()`, and then later `$rule + $options` is passed on to `Validator::rule()`. – rmarscher Apr 09 '12 at 23:53
  • 1
    Thanks for clarification and explanation of the code flow. I finally had a chance to follow up on this and it works perfectly so long as both fields are part of the model. If one is just for input validation (e.g. email address confirmation, where I don't want to store the address twice) then it doesn't work. Instead, having stepped through the code and talked with people on #li3 about input vs data validation, it seems the best way to handle this sort of validation is to catch it in the controller and manually update `$foo->_errors` where `$foo` is the `Entity` object returned by `create()`. – cfogelberg Apr 10 '12 at 22:53
  • Right... I just edited my answer to try to do something that's maybe the best of both worlds. It takes advantage of the `Entity` validates method, but does it in the controller. I included some notes on locking your schema or providing a whitelist to keep additional fields from being saved to the db. I just noticed that `'$_meta['locked']'` is undocumented. I might have to submit a pull request for that. In the meetup we had in February, Nate mentioned he's been rewriting the way schema's work and creating a schema class instead of just an array in the `Model`. Cheers. – rmarscher Apr 13 '12 at 02:38