defaultpersister 1

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

mikehaertl/defaultpersister

Written in PHP by 1 contributor

Contribute

Need Support?


we offer maintenance, support and development services for all our open source projects.

Contact Us

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

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

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

1.0.0 - initial release





43 other PHP projects


phpwkhtmltopdfPHP 716

A slim PHP wrapper around wkhtmltopdf with an easy to use and clean OOP interface

php-pdftkPHP 213

A PDF conversion and form utility based on pdftk

yii2-localeurlsPHP 189

Automatic locale/language management for URLs

YiiRedisPHP 131

A set of wrappers for different data types in redis

yiipasswordPHP 81

Password strategies for Yii

yii2-dockerizedPHP 64

A template for docker based Yii 2 applications

YiiSolrPHP 50

A wrapper for the pecl solr library that provides common Yii constructs, such as models, data providers etc

php-shellcommandPHP 48

A simple object oriented interface to execute shell commands in PHP

Yii-Docs-GeneratorPHP 47

Generates HTML documentation for Yii applications

YiiGitPHP 36

A git wrapper for Yii, allows access to all git commands programatically

YiiElasticSearchPHP 32

Elastic Search client for Yii

YiiCurlPHP 30

A curl library for Yii

YiiStateMachinePHP 28

A state machine behavior for Yii

yii2-streamlogPHP 19

A Yii 2 log target for streams in URL format

oauth2yiiPHP 18

An OAuth2 client / server extension for the Yii framework

restyiiPHP 16

A RESTful extension for Yii.

packagecompressorPHP 16

A Javascript/CSS compressor based on Yii's package system

localeurlsPHP 12

Automatic locale/language management for URLs

php-excel-readerPHP 12

It reads the binary format of XLS files directly and can return values and formats from any cell. This project is the fork of http://code.google.com/p/php-excel-reader/ that, apparently, is no longer maintained.

pdfablePHP 10

A Yii extension to create PDFs with PHPWkHtmlToPdf/wkhtmltopdf

yii-api-vimPHP 8

Yii API manual plugin for VIM

yii2-excel-messagePHP 7

Translate messages via Excel files

xcrudcontrollerPHP 7

A base class to quickly build customized CRUD interfaces.

yii2-bs3activeformPHP 7

A Bootstrap 3 enhanced ActiveForm for Yii 2

php-tmpfilePHP 6

A convenience class for temporary files

handlebarsphpPHP 6

Transpiles handlebars templates into native PHP templates

Yii-Package-ManagerPHP 6

A package manager for Yii

php-orientdbPHP 5

A fast PHP driver for the OrientDB binary protocol.

yii2-apidoc-vimPHP 5

Yii2 apidoc as Vim helpfiles

translatablePHP 4

Transparent attribute translation for ActiveRecords

YiiUsersPHP 4

User management for Yii

flushablePHP 3

Yii dependency that allows to flush records from the cache

Yii-Resource-ManagerPHP 3

Helpers to allow Yii to interact with resources (files) of different types

bs3activeformPHP 2

A lightweight utility to render Bootstrap 3 forms in Yii

AccessRestrictablePHP 2

A Yii ActiveRecordBehavior that automatically applies conditions for access restriction to every query.

YiiEmailerPHP 2

Emailing functions for Yii

hybridauthmanagerPHP 1

An AuthManager for Yii that stores the hierarchy in a flat PHP file and the assignments in DB

YiiYaaPHP 1

YAA is an additional abstraction layer for Yii that aggregates a number of child models into a clean single model that is easy to cache

YiiLinkablePHP 1

A simple extension for Yii allowing easy and consistent access to model URLs and appropriate anchor text.

twittonioPHP

simple useless twitter client

yii2-base-appPHP

An alternative Yii2 application template for purists

YiiAbstractArrayModelPHP

Work with PHP files in Active Record way

xreturnablePHP

Yii extension to create URLs that allow to return to a page by storing its GET Parameters on a stack.