PHPackages                             mikehaertl/defaultpersister - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mikehaertl/defaultpersister

ActiveYii-extension[Utility &amp; Helpers](/categories/utility)

mikehaertl/defaultpersister
===========================

Yii extension to save and restore model values in user session.

1.1.0(13y ago)127MITPHPPHP &gt;=5.0.0

Since Mar 29Pushed 13y ago1 watchersCompare

[ Source](https://github.com/mikehaertl/defaultpersister)[ Packagist](https://packagist.org/packages/mikehaertl/defaultpersister)[ Docs](https://github.com/mikehaertl/defaultpersister)[ RSS](/packages/mikehaertl-defaultpersister/feed)WikiDiscussions master Synced 4w ago

READMEChangelogDependenciesVersions (2)Used By (0)

DefaultPersister
================

[](#defaultpersister)

This is a behavior for `CModel` (`CFormModel`, `CActiveRecord`) which allows to save the set of current attribute values as defaults for the current user and restore them at a later time.

\##Requirements

Should work with any 1.1.x version. Not tested with 1.0.x.

\##Usage

When this behavior is attached to a model, the current model values can be saved as default values with a simple command:

```
$model->saveAsDefaults();
```

This will save all configured attributes in user state (session). To load these defaults back into the model you can use:

```
$model->loadDefaults();
```

It's also possible to save or load only some attributes:

```
// Will merge with already saved defaults
$model->saveAsDefaults('name');
$model->saveAsDefaults(array('status','project_id'));

$model->loadDefaults('name');
$model->loadDefaults(array('name','project_id'));
```

To only load attributes that are safe in the current scenario, you can override the configured value of `safeOnly` (see below):

```
// true indicates that only safe attributes should be loaded
$model->loadDefaults(null,true);
```

Finally to clear the saved default values use:

```
$model->resetDefaults();       // Reset all defaults
$model->resetDefaults('name'); // Reset specific attribute
```

\##Configuration

Like all behaviors this extension has to be configured in the `behaviors()` method of a model:

```
public function behaviors()
{
    return array(
        'defaults'=>array(
            'class'=>'ext.defaultpersister.AttributeDefaultsPersister',
            'attributes'=>array('name','status','project_id'),
        ),
    );
}
```

All attributes that should be saved with `saveAsDefaults()` must be listed in the `attributes` property of the behavior.

The complete list of configuration options is:

- `attributes` : list of attribute names that can be saved / loaded
- `safeOnly` : if true, only attributes that are safe in the current scenario will be loaded with `loadDefaults()`. Default is `false`.
- `stateKeyPrefix` : prefix for the user state key that is used to store defaults. Actual key name will be prefix + model class name. Defaults to `default_`.

If `loadDefaults()` is called before any values where ever saved with `saveAsDefaults()` the model is scanned for a method `attributeDefaults()`. If this method is found the returned values (name/value pairs) will be set as default. If no such method is available, `loadDefaults()` will do nothing in this case.

Since Version 1.1.0 `resetDefaults()` can be used to clear all attributes, one attribute or a list of attributes default values.

If YII\_DEBUG is true, this behavior will trace some messages under the category `application.behavior.defaultpersister`.

Example
-------

[](#example)

One scenario where this behavior can come in handy is e.g. when a model is used as complex filter model for a datagrid. Think of a backend area with pages for users and projects, each showing a filter form and a datagrid. Changes in the filter form trigger a AJAX grid update. Whenever backend personnel accesses such a page the last filter settings should be restored for convenience.

A controller action for this could look like:

```
public function actionUserList()
{
    $filter=new User('filter');
    $filter->loadDefaults();

    // Set filter attributes on Ajax request and save them as default
    if (($isAjax=isset($_GET['ajax'])) && isset($_GET['User']))
    {
        $filter->attributes=$_GET['User'];
        if (!$filter->validate())   // Invalid filter settings!
            return;
        $filter->saveAsDefaults();
    }

    // Similar to the search() method in Yii's default CRUD models,
    // this method creates a CActiveDataProvider from the current
    // attribute values:
    $data=$filter->getDataProvider();

    if ($isAjax)
        // render only the partial for the data grid:
        $this->renderPartial('_userGrid',array(
            'data'=>$data,
        ));
    else
        // render complete view with filter and data grid
        $this->render('userList',array(
            'filter'=>$filter,
            'data'=>$data,
        ));
}
```

\##Changelog

### 1.1.0

[](#110)

- Fixed: Model defined attributes that are not in DB will also be set in AR
- Added resetDefaults() method

### 1.0.0 - initial release

[](#100---initial-release)

###  Health Score

26

—

LowBetter than 41% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

4841d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ed4cc6f6e2a51bf286f02ad0def4ee6736be32aea75bfdcd43047696cec56869?d=identicon)[mike](/maintainers/mike)

---

Top Contributors

[![mikehaertl](https://avatars.githubusercontent.com/u/675062?v=4)](https://github.com/mikehaertl "mikehaertl (1 commits)")

---

Tags

modelBehavioryii

### Embed Badge

![Health badge](/badges/mikehaertl-defaultpersister/health.svg)

```
[![Health](https://phpackages.com/badges/mikehaertl-defaultpersister/health.svg)](https://phpackages.com/packages/mikehaertl-defaultpersister)
```

###  Alternatives

[sjaakp/yii2-taggable

Manage tags of ActiveRecord in Yii2.

2931.8k](/packages/sjaakp-yii2-taggable)[baibaratsky/yii2-serialized-attributes-behavior

Yii2 Serialized Attributes Behavior

1175.1k9](/packages/baibaratsky-yii2-serialized-attributes-behavior)[raoul2000/yii-simple-workflow

A simple workflow engine for Yii 1

278.2k](/packages/raoul2000-yii-simple-workflow)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
