beforeSave callback

@param Model $model The current model being used
@param array $options Callback options

@return mixed
326523
public function beforeSave(Model $model, $options = array()) {
		$fields = (array)$this->__settings[$model->alias]['fields'];
		$scope = (array)$this->__settings[$model->alias]['scope'];
		$conditions = !empty($this->__settings[$model->alias]['conditions']) ? (array)$this->__settings[$model->alias]['conditions'] : array();
		$slugfield = $this->__settings[$model->alias]['slugfield'];
		$hasFields = true;

		foreach ($fields as $field) {
			if (!$model->hasField($field)) {
				$hasFields = false;
			}

			if (!isset($model->data[$model->alias][$field])) {
				$hasFields = false;
			}
		}

		if ($hasFields && $model->hasField($slugfield) && ($this->__settings[$model->alias]['overwrite'] || empty($model->id))) {
			$toSlug = array();

			foreach ($fields as $field) {
				$toSlug[] = $model->data[$model->alias][$field];
			}

			$toSlug = join(' ', $toSlug);

			$slug = Inflector::slug($toSlug, $this->__settings[$model->alias]['separator']);

			if ($this->__settings[$model->alias]['lower']) {
				$slug = strtolower($slug);
			}

			if (strlen($slug) > $this->__settings[$model->alias]['length']) {
				$slug = substr($slug, 0, $this->__settings[$model->alias]['length']);
			}

			$conditions[$model->alias . '.' . $slugfield . ' LIKE'] = $slug . '%';

			if (!empty($model->id)) {
				$conditions[$model->alias . '.' . $model->primaryKey . ' !='] = $model->id;
			}

			if (!empty($scope)) {
				foreach ($scope as $s) {
					if (isset($model->data[$model->alias][$s])) {
						$conditions[$model->alias . '.' . $s] = $model->data[$model->alias][$s];
					}
				}
			}

			$sameUrls = $model->find('all', array(
				'recursive' => -1,
				'conditions' => $conditions
			));

			$sameUrls = (!empty($sameUrls))
				? Hash::extract($sameUrls, '{n}.' . $model->alias . '.' . $slugfield)
				: array();

			if (!empty($sameUrls)) {
				if (in_array($slug, $sameUrls)) {
					$begginingSlug = $slug;
					$index = 1;

					while ($index > 0) {
						if (!in_array($begginingSlug . $this->__settings[$model->alias]['separator'] . $index, $sameUrls)) {
							$slug = $begginingSlug . $this->__settings[$model->alias]['separator'] . $index;
							$index = -1;
						}

						$index++;
					}
				}
			}

			$model->data[$model->alias][$slugfield] = $slug;
		}

		return parent::beforeSave($model);
	}
617497
protected function save($model)
    {
        $method = $this->saveMethod;

        if (!method_exists($model, $method)) {
            throw new SaveMethodNotFoundException(get_class($model), $method);
        }

        return $model->$method();
    }
168967
private function doCommitUpdate(Model $model)
    {
        $this->dispatchLifecycleEvent(Events::preUpdate, $model);

        $this->getPersisterFor($model->getType())->update($model);
        // Should the model always reload? Or should the commit be assumed correct and just clear the new/dirty state?
        $model->reload();

        $this->dispatchLifecycleEvent(Events::postUpdate, $model);
        return $model;
    }
172524
public function flush($model = null, array $options = array())
    {
        $this->errorIfClosed();
        $this->unitOfWork->commit($model, $options);
    }
46747
public function beforeSave(Model $model, $options = array()) {
        $alias = $model->alias;

        if (empty($model->data[$alias])) {
            return true;
        }

        // Loop through the data and upload the file
        foreach ($model->data[$alias] as $field => $file) {
            if (empty($this->settings[$alias][$field])) {
                continue;
            }

            // Gather attachment settings
            $attachment = $this->_settingsCallback($model, $this->settings[$alias][$field]);
            $data = array();

            // Initialize Transit
            $transit = new Transit($file);
            $transit->setDirectory($attachment['tempDir']);

            $this->_uploads[$alias] = $transit;

            // Set transformers and transporter
            $this->_addTransformers($model, $transit, $attachment);
            $this->_setTransporter($model, $transit, $attachment);

            // Attempt upload or import
            try {
                $overwrite = $attachment['overwrite'];
                $response = null;

                // File upload
                if (is_array($file)) {
                    $response = $transit->upload($overwrite);

                // Remote import
                } else if (preg_match('/^http/i', $file)) {
                    $response = $transit->importFromRemote($overwrite, $attachment['curl']);

                // Local import
                } else if (file_exists($file)) {
                    $response = $transit->importFromLocal($overwrite);

                // Stream import
                } else if (!empty($file)) {
                    $response = $transit->importFromStream($overwrite);
                }

                // Successful upload or import
                if ($response) {
                    $dbColumnMap = array($attachment['dbColumn']);
                    $transportConfig = array($this->_prepareTransport($attachment));

                    // Rename and move file
                    $data[$attachment['dbColumn']] = $this->_renameAndMove($model, $transit->getOriginalFile(), $attachment);

                    // Fetch exif data before transforming
                    $metaData = array();

                    foreach ($transit->getOriginalFile()->toArray() as $key => $value) {
                        if (substr($key, 0, 4) === 'exif' && $value) {
                            $metaData[$key] = $value;
                        }
                    }

                    // Transform the files and save their path
                    if ($attachment['transforms']) {
                        $transit->transform();

                        $transformedFiles = $transit->getTransformedFiles();
                        $count = 0;

                        foreach ($attachment['transforms'] as $transform) {
                            if ($transform['self']) {
                                $tempFile = $transit->getOriginalFile();
                                $dbColumnMap[0] = $transform['dbColumn'];

                            } else {
                                $tempFile = $transformedFiles[$count];
                                $dbColumnMap[] = $transform['dbColumn'];
                                $count++;

                                $transportConfig[] = $this->_prepareTransport($transform);
                            }

                            $data[$transform['dbColumn']] = $this->_renameAndMove($model, $tempFile, $transform);
                        }
                    }

                    $metaData = array_merge($transit->getOriginalFile()->toArray(), $metaData);

                    // Transport the files and save their remote path
                    if ($attachment['transport']) {
                        if ($transportedFiles = $transit->transport($transportConfig)) {
                            foreach ($transportedFiles as $i => $transportedFile) {
                                $data[$dbColumnMap[$i]] = $transportedFile;
                            }
                        }
                    }
                }

            // Trigger form errors if validation fails
            } catch (ValidationException $e) {
                $dbColumns = array_merge(array($attachment['dbColumn']), array_keys($attachment['transforms']));

                foreach ($dbColumns as $dbCol) {
                    unset($model->data[$alias][$dbCol]);
                }

                // Allow empty uploads
                if ($attachment['allowEmpty']) {
                    continue;
                }

                // Invalidate and stop
                $model->invalidate($field, __d('uploader', $e->getMessage()));

                if ($attachment['stopSave']) {
                    return false;
                }

            // Log exceptions that shouldn't be shown to the client
            } catch (Exception $e) {
                $model->invalidate($field, __d('uploader', $e->getMessage()));

                $this->log($e->getMessage(), LOG_DEBUG);

                // Rollback the files since it threw errors
                $transit->rollback();

                if ($attachment['stopSave']) {
                    return false;
                }
            }

            // Save file meta data
            $cleanup = $data;

            if ($attachment['metaColumns'] && $data && !empty($metaData)) {
                foreach ($attachment['metaColumns'] as $method => $column) {
                    if (isset($metaData[$method]) && $column) {
                        $data[$column] = $metaData[$method];
                    }
                }
            }

            // Merge upload data with model data
            if ($data) {
                $model->data[$alias] = $data + $model->data[$alias];
            }

            // Keep it in a loop, so it will delete all files
            // If we are doing an update, delete the previous files that are being replaced
            if ($model->id && $cleanup) {
                $this->_cleanupOldFiles($model, $cleanup);
            }
        }

        return true;
    }
892973
public function beforeValidationOnCreate(Event $event, Model $model)
    {
        if($model instanceof ITimestampable) {
            $now = $this->getNow();
            if(!$model->getCreatedAt()) {
                $model->setCreatedAt($now);
            }
            if(!$model->getUpdatedAt()) {
                $model->setUpdatedAt($now);
            }
        }
    }
1172779
protected function resolvePendingOps($model)
    {
        $name = $model->getMeta()->getNSModelName();
        if (isset($this->_pendingOps[$name])) {
            $todoActions = $this->_pendingOps[$name];
            foreach ($todoActions as $todoAction) {
                list($callback, $kwargs) = $todoAction;
                $kwargs['relatedModel'] = $model;
                $callback($kwargs);
            }
            unset($this->_pendingOps[$name]);
        }
    }
929015
protected function saveColumns(Model $model)
    {
        /** @var \T4\Orm\Model $class */
        $class = get_class($model);
        $columns = $class::getColumns();
        $relations = $class::getRelations();
        $cols = [];
        $sets = [];
        $data = [];

        foreach ($columns as $column => $def) {
            if (isset($model->{$column}) && null === $model->{$column} && isset($def['default'])) {
                $sets[$column] = ':' . $column;
                $data[':'.$column] = $def['default'];
            } else {
                $cols[] = $column;
                $sets[$column] = ':' . $column;
                switch ($def['type']) {
                    case 'boolean':
                        $data[':' . $column] = (int)$model->{$column};
                        break;
                    default:
                        $data[':' . $column] = $model->{$column};
                        break;
                }
            }
        }

        foreach ($relations as $rel => $def) {
            switch ($def['type']) {
                case $class::BELONGS_TO:
                    $column = $class::getRelationLinkName($def);
                    if (!in_array($column, $cols)) {
                        // todo: test this!
                        //if (isset($model->{$column}) && !is_null($model->{$column})) {
                        if (isset($model->{$column})) {
                            $sets[$column] = ':' . $column;
                            $data[':'.$column] = $model->{$column};
                        } elseif (isset($model->{$rel}) && $model->{$rel} instanceof Model) {
                            $sets[$column] = ':' . $column;
                            $data[':'.$column] = $model->{$rel}->getPk();
                        }
                    }
                    break;
            }
        }

        $connection = $class::getDbConnection();
        if ($model->isNew()) {
            $query = new Query();
            $query->insert($class::getTableName())
                ->values($sets)
                ->params($data);
            $connection->execute($query);
            $model->{$class::PK} = $connection->lastInsertId();
        } else {
            $query = new Query();
            $query->update($class::getTableName())
                ->values($sets)
                ->where($this->quoteName($class::PK) . '='. $model->getPk())
                ->params($data);
            $connection->execute($query);
        }

        return $model;

    }
535650
public function save(Model $model)
    {
        $model->setAttribute($this->getPlainForeignKey(), $this->getParentKey());

        return $model->save() ? $model : false;
    }
644724
public function beforeDelete(Model $Model, $cascade = true) {
		if ($this->settings[$Model->alias]['auto'] === false) {
			return true;
		}
		if (!$Model->ShadowModel) {
			return true;
		}
		foreach ($Model->hasAndBelongsToMany as $assocAlias => $a) {
			if (isset($Model->{$assocAlias}->ShadowModel->_schema[$Model->alias])) {
				$joins = $Model->{$a['with']}->find('all', array('recursive' => -1, 'conditions' => array($a['foreignKey'] => $Model->
							id)));
				$this->deleteUpdates[$Model->alias][$assocAlias] = Hash::extract($joins, '{n}.' . $a['with'] . '.' . $a['associationForeignKey']);
			}
		}
		return true;
	}
409185
public function save(Model $model)
    {
        $foreignKey = $this->getForeignKeyName();
        $parentKeyValue = $this->getParentKey();

        if (is_array($foreignKey)) { //Check for multi-columns relationship
            foreach ($foreignKey as $index => $key) {
                $model->setAttribute($key, $parentKeyValue[$index]);
            }
        } else {
            $model->setAttribute($foreignKey, $parentKeyValue);
        }

        return $model->save() ? $model : false;
    }
222094
public function beforeSave($event, $entity, $options)
    {
        $auth = Configure::read('GlobalAuth');
        $id = $auth['id'];

        if ($entity->isNew()) {
            if ($this->config('created_by')) {
                $entity->set($this->config('created_by'), $id);
            }
        }

        if ($this->config('modified_by')) {
            $entity->set($this->config('modified_by'), $id);
        }
    }
1329501
public function create($model = null, $options = [])
    {
        $defaults = [
            'inputDefaults' => [
                'div' => [
                    'class' => 'form-group',
                ],
                'label' => [

                    'class' => 'control-label',
                ],
                'class' => 'form-control',
                'error' => [
                    'attributes' => [
                        'wrap' => 'p',
                        'class' => 'text-danger',
                    ],
                ],
            ],
            'class' => null,
            'role' => 'form',
        ];

        $options = Hash::merge($defaults, $options);
        return parent::create($model, $options);
    }
3335
private function doCommitCreate(Model $model)
    {
        $this->dispatchLifecycleEvent(Events::preCreate, $model);

        $this->getPersisterFor($model->getType())->create($model);
        $model->getState()->setNew(false);
        // Should the model always reload? Or should the commit be assumed correct and just clear the new/dirty state?
        $model->reload();

        $this->dispatchLifecycleEvent(Events::postCreate, $model);
        return $model;
    }
825210
public function beforeSave(Model &$model)
    {

        if ($model->isNew()) {
            if (empty($model->parent)) {
                $this->insertModelAsLastRoot($model);
            } else {
                $this->insertModelAsLastChildOf($model, $model->parent);
            }
        } else {
            /** @var \T4\Orm\Model $class */
            $class = get_class($model);
            $oldParent = empty($model->__prt) ? null : $class::findByPk($model->__prt);
            if ($oldParent != $model->parent) {
                $model->refreshTreeColumns();
                if (empty($model->parent)) {
                    $this->insertModelAsLastRoot($model);
                } else {
                    /** @var \T4\Dbal\Connection $connection */
                    $connection = $class::getDbConnection();
                    $query = new Query();
                    $query
                        ->select('count(*)')
                        ->from($class::getTableName())
                        ->where('__id=:id AND __lft>:lft AND __rgt<:rgt')
                        ->params([':id' => $model->parent->getPk(), ':lft'=>$model->__lft, ':rgt'=>$model->__rgt]);

                    if ($connection->query($query)->fetchScalar() > 0) {
                        throw new Exception('Parent must not be in children!');
                    }

                    $this->insertModelAsLastChildOf($model, $model->parent);
                }
            }
        }

        return true;

    }
646381
function(model, options) {
      var coll = this;
      options || (options = {});
      model = this._prepareModel(model, options);
      if (!model) return false;
      var success = options.success;
      options.success = function(nextModel, resp, xhr) {
        coll.add(nextModel, options);
        if (success) success(nextModel, resp, xhr);
      };
      model.save(null, options);
      return model;
    }
1176170
function(model, options) {
      options = options ? _.clone(options) : {};
      var wait = options.wait;
      model = this._prepareModel(model, options);
      if (!model) return false;
      if (!wait) this.add(model, options);
      var collection = this;
      var success = options.success;
      options.success = function(m, resp, callbackOpts) {
        if (wait) collection.add(m, callbackOpts);
        if (success) success.call(callbackOpts.context, m, resp, callbackOpts);
      };
      model.save(null, options);
      return model;
    }