Note that there are some explanatory texts on larger screens.

plurals
  1. POCakePHP Model::save allowed partially blank data during record insertion
    text
    copied!<p>I was investigating CakePHP (2.3.4) Model::save method to insert new records and ran into a little snag:</p> <pre><code>//Two fields provided, email field intended to fail validation $data = array('Member' =&gt; array( 'username' =&gt; 'hello', 'email' =&gt; 'world' )); $this-&gt;Member-&gt;create(); var_dump($this-&gt;Member-&gt;save($data, true)); </code></pre> <p>The above save() will return false and no data will be written to the database. However if I change the data to:</p> <pre><code>//One field provided, intended to pass validation $data = array('Member' =&gt; array( 'username' =&gt; 'hello' )); </code></pre> <p>then save() will attempt to write a new record to database with a blank email field. I realize that skipping validation for unspecified fields might be a useful behavior during updates, but is there a CakePHP recommended way to handle partially empty data sets when creating new records? Thanks a lot.</p> <p><strong>Edit:</strong> Thanks to Sam Delaney for the tip. In case anybody else gets stumped, this did the trick: <a href="http://book.cakephp.org/2.0/en/models/data-validation.html#required" rel="nofollow">CakePHP Data Validation: field 'required' key</a></p> <blockquote> <p>This key accepts either a boolean, or create or update. Setting this key to true will make the field always required. While setting it to create or update will make the field required only for update or create operations. <strong>If ‘required’ is evaluated to true, the field must be present in the data array</strong>. For example, if the validation rule has been defined as follows:</p> </blockquote> <p>I had originally baked the model and forgotten that <code>required =&gt; true</code> was left out of the validation rule. Setting it to <code>true</code> or <code>'create'</code> would've avoided me blank records getting inserted due to gibberish data array.</p>
 

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