lithium\data\Model::save PHP Method

save() public method

For example, to create a new record or document: $post = Posts::create(); // Creates a new object, which doesn't exist in the database yet $post->title = "My post"; $success = $post->save(); It is also used to update existing database objects, as in the following: $post = Posts::first($id); $post->title = "Revised title"; $success = $post->save(); By default, an object's data will be checked against the validation rules of the model it is bound to. Any validation errors that result can then be accessed through the errors() method. if (!$post->save($someData)) { return array('errors' => $post->errors()); } To override the validation checks and save anyway, you can pass the 'validate' option: $post->title = "We Don't Need No Stinkin' Validation"; $post->body = "I know what I'm doing."; $post->save(null, array('validate' => false)); By default only validates and saves fields from the schema (if available). This behavior can be controlled via the 'whitelist' and 'locked' options.
See also: lithium\data\Model::$validates
See also: lithium\data\Model::validates()
See also: lithium\data\Entity::errors()
public save ( object $entity, array $data = null, array $options = [] ) : boolean
$entity object The record or document object to be saved in the database. This parameter is implicit and should not be passed under normal circumstances. In the above example, the call to `save()` on the `$post` object is transparently proxied through to the `Posts` model class, and `$post` is passed in as the `$entity` parameter.
$data array Any data that should be assigned to the record before it is saved.
$options array Options: - `'callbacks'` _boolean_: If `false`, all callbacks will be disabled before executing. Defaults to `true`. - `'validate'` _boolean|array_: If `false`, validation will be skipped, and the record will be immediately saved. Defaults to `true`. May also be specified as an array, in which case it will replace the default validation rules specified in the `$validates` property of the model. - `'events'` _string|array_: A string or array defining one or more validation _events_. Events are different contexts in which data events can occur, and correspond to the optional `'on'` key in validation rules. They will be passed to the validates() method if `'validate'` is not `false`. - `'whitelist'` _array_: An array of fields that are allowed to be saved to this record. When unprovided will - if available - default to fields of the current schema and the `'locked'` option is not `false`. - `'locked'` _boolean_: Whether to use schema for saving just fields from the schema or not. Defaults to `true`.
return boolean Returns `true` on a successful save operation, `false` on failure.
    public function save($entity, $data = null, array $options = array())
    {
        $self = static::_object();
        $_meta = array('model' => get_called_class()) + $self->_meta;
        $_schema = $self->schema();
        $defaults = array('validate' => true, 'events' => $entity->exists() ? 'update' : 'create', 'whitelist' => null, 'callbacks' => true, 'locked' => $self->_meta['locked']);
        $options += $defaults;
        $params = compact('entity', 'data', 'options');
        $filter = function ($self, $params) use($_meta, $_schema) {
            $entity = $params['entity'];
            $options = $params['options'];
            if ($params['data']) {
                $entity->set($params['data']);
            }
            if (($whitelist = $options['whitelist']) || $options['locked']) {
                $whitelist = $whitelist ?: array_keys($_schema->fields());
            }
            if ($rules = $options['validate']) {
                $events = $options['events'];
                $validateOpts = compact('events', 'whitelist');
                if (is_array($rules)) {
                    $validateOpts['rules'] = $rules;
                }
                if (!$entity->validates($validateOpts)) {
                    return false;
                }
            }
            $type = $entity->exists() ? 'update' : 'create';
            $query = $self::invokeMethod('_instance', array('query', compact('type', 'whitelist', 'entity') + $options + $_meta));
            return $self::connection()->{$type}($query, $options);
        };
        if (!$options['callbacks']) {
            return $filter(get_called_class(), $params);
        }
        return static::_filter(__FUNCTION__, $params, $filter);
    }

Usage Example

Example #1
0
 /**
  * automatically adds timestamps on saving.
  *
  * In case of creation it correctly fills the `created` field with a unix timestamp.
  * Same holds true for `updated` on updates, accordingly.
  *
  * @see lithium\data\Model
  * @param object $entity current instance
  * @param array $data Any data that should be assigned to the record before it is saved.
  * @param array $options additional options
  * @return boolean true on success, false otherwise
  * @filter
  */
 public function save($entity, $data = array(), array $options = array())
 {
     if (!empty($data)) {
         $entity->set($data);
     }
     $schema = $entity->schema();
     foreach ($schema->fields() as $name => $meta) {
         if (isset($meta['type']) && $meta['type'] !== 'list') {
             continue;
         }
         if (is_string($entity->{$name})) {
             $listData = explode("\n", $entity->{$name});
             array_walk($listData, function (&$val) {
                 $val = trim($val);
             });
             $entity->{$name} = $listData;
         }
     }
     $versions = static::meta('versions');
     if (!isset($options['callbacks']) || $options['callbacks'] !== false) {
         $field = $entity->exists() ? 'updated' : 'created';
         $entity->set(array($field => time()));
         if ($versions === true || is_callable($versions) && $versions($entity, $options)) {
             $version_id = Versions::add($entity, $options);
             if ($version_id) {
                 $entity->set(compact('version_id'));
             }
         }
     }
     $result = parent::save($entity, null, $options);
     if ($result && isset($field) && $field == 'created') {
         if ($versions === true || is_callable($versions) && $versions($entity, $options)) {
             $version_id = Versions::add($entity, array('force' => true));
             if ($version_id) {
                 $entity->set(compact('version_id'));
                 return $entity->save(null, array('callbacks' => false));
             }
         }
     }
     return $result;
 }
All Usage Examples Of lithium\data\Model::save