Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I use CakePHP's model validation messages instead of the controller's setFlash messages?
    primarykey
    data
    text
    <p><strong>Description</strong></p> <p>I have a simple form on every page of my site - a single input and a submit button. The point is just for the user to enter his/her email address and hit submit.</p> <p>It works if the data is an email address - but if it's not a valid email address, it submits the form, the page reloads (or whatever), and the flash message comes up instead of my model's more specific "not a valid email" error.</p> <p><strong>Question:</strong></p> <p>So, how do I use the model's validation message instead of the controller's generic one?</p> <p><strong>The form:</strong></p> <pre><code>echo $this-&gt;Form-&gt;create('Email', array('class'=&gt;'form1', 'url'=&gt;'/emails/add', 'inputDefaults'=&gt;array('label'=&gt;false))); echo $this-&gt;Form-&gt;input('Email.email'); echo $this-&gt;Form-&gt;end('SIGN-UP'); </code></pre> <p><strong>The email controller "add" function (or method?):</strong> </p> <pre><code>function add() { if (!empty($this-&gt;data)) { $this-&gt;Email-&gt;create(); if ($this-&gt;Email-&gt;save($this-&gt;data)) { $this-&gt;Session-&gt;setFlash(__('The email address has been saved', true)); $this-&gt;redirect($this-&gt;referer()); } else { $this-&gt;Session-&gt;setFlash(__('The email address could not be saved. Please, try again.', true)); $this-&gt;set('error', 'custom error here'); $this-&gt;redirect($this-&gt;referer()); } } } </code></pre> <p><strong>And the email model:</strong></p> <pre><code>class Email extends AppModel { var $name = 'Email'; var $validate = array( 'email' =&gt; array( 'is_valid' =&gt; array( //named whatever we want 'rule' =&gt; 'notEmpty', 'rule' =&gt; array('email', true), 'message' =&gt; 'Please supply a valid email address.', 'last' =&gt; true //causes it to not check the next rule if this one fails ), 'is_unique' =&gt; array( //named whatever we want 'rule' =&gt; 'isUnique', 'message' =&gt; 'That email address is already in our database.' ) ), ); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload