<p>In your model you can override <a href="http://buildwithcraft.com/classreference/models/BaseModel#setAttribute-detail" rel="nofollow">setAttribute()</a>, which covers calling <code>setAttribute('foo', 'bar')</code> directly as well as <code>$model-&gt;foo = 'bar'</code>.</p>

<pre><code>public function setAttribute($name, $value)
{
    if ($name == 'foo')
    {
        // Not sure if your value will be a dateTime object, string, etc.
        // But check to see if it's &lt; than today's current date.  If so,
        // set $value = new DateTime();
    }

    parent::setAttribute($name, $value)
}
</code></pre>

CC BY-SA 3.0
2015-04-06T15:47:11.507Z
2015-04-06T15:47:11.507Z
Brad Bell
<p>I want to ensure that any attempt to set a date attribute on a model by way of populateModel() or myModel->foo = 'bar' (basically any method of setting a value) is intercepted so I can set a default if the value isn't valid.</p>

<p>Put another way, if you attempt to set a date prior to today (or a string that's not a date), I want to set the attribute to be today's date.</p>

<p>Currently I'm doing that in my populateModel() method but that doesn't catch the setAttribute('foo') approach or the myModel->foo approach.</p>

<p>For example in Laravel, we can create a setter method: setFooAttribute() so I was hoping for something similar.</p>

<models>
Is there a way to define an attribute setter method on a model?
# Is there a way to define an attribute setter method on a model?

(Asked by: username_0 on 2015-04-06)

I want to ensure that any attempt to set a date attribute on a model by way of populateModel() or myModel->foo = 'bar' (basically any method of setting a value) is intercepted so I can set a default if the value isn't valid.

Put another way, if you attempt to set a date prior to today (or a string that's not a date), I want to set the attribute to be today's date.

Currently I'm doing that in my populateModel() method but that doesn't catch the setAttribute('foo') approach or the myModel->foo approach.

For example in Laravel, we can create a setter method: setFooAttribute() so I was hoping for something similar.

**Tags:** models

---

## 1 answers

### Answer by username_1 on 2015-04-06. Score: 2 | Accepted answer

In your model you can override setAttribute(), which covers calling setAttribute('foo', 'bar') directly as well as $model->foo = 'bar'.
public function setAttribute($name, $value)
{
    if ($name == 'foo')
    {
        // Not sure if your value will be a dateTime object, string, etc.
        // But check to see if it's < than today's current date.  If so,
        // set $value = new DateTime();
    }

    parent::setAttribute($name, $value)
}


---

