save() публичный Метод

### Options The options array accepts the following keys: - atomic: Whether to execute the save and callbacks inside a database transaction (default: true) - checkRules: Whether or not to check the rules on entity before saving, if the checking fails, it will abort the save operation. (default:true) - associated: If true it will save 1st level associated entities as they are found in the passed $entity whenever the property defined for the association is marked as dirty. If an array, it will be interpreted as the list of associations to be saved. It is possible to provide different options for saving on associated table objects using this key by making the custom options the array value. If false no associated records will be saved. (default: true) - checkExisting: Whether or not to check if the entity already exists, assuming that the entity is marked as not new, and the primary key has been set. ### Events When saving, this method will trigger four events: - Model.beforeRules: Will be triggered right before any rule checking is done for the passed entity if the checkRules key in $options is not set to false. Listeners will receive as arguments the entity, options array and the operation type. If the event is stopped the rules check result will be set to the result of the event itself. - Model.afterRules: Will be triggered right after the checkRules() method is called for the entity. Listeners will receive as arguments the entity, options array, the result of checking the rules and the operation type. If the event is stopped the checking result will be set to the result of the event itself. - Model.beforeSave: Will be triggered just before the list of fields to be persisted is calculated. It receives both the entity and the options as arguments. The options array is passed as an ArrayObject, so any changes in it will be reflected in every listener and remembered at the end of the event so it can be used for the rest of the save operation. Returning false in any of the listeners will abort the saving process. If the event is stopped using the event API, the event object's result property will be returned. This can be useful when having your own saving strategy implemented inside a listener. - Model.afterSave: Will be triggered after a successful insert or save, listeners will receive the entity and the options array as arguments. The type of operation performed (insert or update) can be determined by checking the entity's method isNew, true meaning an insert and false an update. - Model.afterSaveCommit: Will be triggered after the transaction is commited for atomic save, listeners will receive the entity and the options array as arguments. This method will determine whether the passed entity needs to be inserted or updated in the database. It does that by checking the isNew method on the entity. If the entity to be saved returns a non-empty value from its errors() method, it will not be saved. ### Saving on associated tables This method will by default persist entities belonging to associated tables, whenever a dirty property matching the name of the property name set for an association in this table. It is possible to control what associations will be saved and to pass additional option for saving them. Only save the comments association $articles->save($entity, ['associated' => ['Comments']); Save the company, the employees and related addresses for each of them. For employees do not check the entity rules $companies->save($entity, [ 'associated' => [ 'Employees' => [ 'associated' => ['Addresses'], 'checkRules' => false ] ] ]); Save no associations $articles->save($entity, ['associated' => false]);
public save ( Cake\Datasource\EntityInterface $entity, $options = [] )
$entity Cake\Datasource\EntityInterface
Пример #1
1
 /**
  * test WHERE conditions against unary expression.
  *
  * @return void
  */
 public function testUnaryExpression()
 {
     $this->table->addColumn('user-birth-date', ['type' => 'date'], false);
     $first = $this->table->get(1);
     $first->set('user-birth-date', time());
     $this->table->save($first);
     $second = $this->table->find('all', ['eav' => true])->where(['user-birth-date IS' => null])->order(['id' => 'ASC'])->first();
     $this->assertTrue(!empty($second) && $second->get('id') == 2);
 }
Пример #2
0
 public function saveSettingsAction()
 {
     try {
         $this->cronSettings->save($this->cronSettings->get(1)->set($_POST));
         $this->flasher->success('Saved general cron settings!');
     } catch (\Exception $e) {
         $this->flasher->error("Could not save general cron settings: " . $e->getMessage());
     }
     $this->redirect('/admin/crons');
 }
Пример #3
0
 /**
  * ResetSlugs method.
  *
  * Regenerate all slugs. On large dbs this can take more than 30 seconds - a time
  * limit is set to allow a minimum 100 updates per second as a preventative measure.
  *
  * Note that you should use the Reset behavior if you need additional functionality such
  * as callbacks or timeouts.
  *
  * @param array $params
  * @return bool Success
  */
 public function resetSlugs($params = [])
 {
     if (!$this->_table->hasField($this->_config['field'])) {
         throw new Exception('Table does not have field ' . $this->_config['field']);
     }
     $defaults = ['page' => 1, 'limit' => 100, 'fields' => array_merge([$this->_table->primaryKey()], $this->_config['label']), 'order' => $this->_table->displayField() . ' ASC', 'conditions' => $this->_config['scope'], 'overwrite' => true];
     $params = array_merge($defaults, $params);
     $count = $this->_table->find('all', compact('conditions'))->count();
     $max = ini_get('max_execution_time');
     if ($max) {
         set_time_limit(max($max, $count / 100));
     }
     $this->_table->behaviors()->Slugged->config($params, null, false);
     while ($records = $this->_table->find('all', $params)->toArray()) {
         foreach ($records as $record) {
             $record->isNew(true);
             $options = ['validate' => true, 'fieldList' => array_merge([$this->_table->primaryKey(), $this->_config['field']], $this->_config['label'])];
             if (!$this->_table->save($record, $options)) {
                 throw new Exception(print_r($this->_table->errors(), true));
             }
         }
         $params['page']++;
     }
     return true;
 }
 /**
  * testSave
  *
  * @retun void
  * @access public
  */
 public function testSave()
 {
     $data = ['nome' => 'Produto 4', 'valor' => '5.000,00'];
     $entidade = $this->Produtos->newEntity($data);
     $resultado = $this->Produtos->save($entidade);
     $this->assertInstanceOf('Cake\\ORM\\Entity', $resultado);
     $this->assertEquals('5000.00', $entidade->get("valor"));
     $this->assertEquals('5000.00', $resultado->get("valor"));
 }
 /**
  *
  * @param bool $publicadoEm Valor para colocar no publicado_em
  * @param bool $autorizadoEm Valor para colocar no autorizado_em
  * @return \Cake\Datasource\EntityInterface|mixed
  */
 private function __preparaNoticia($publicadoEm = false, $autorizadoEm = false)
 {
     $noticia = $this->Noticias->newEntity(['titulo' => 'Exemplo 1', 'conteudo' => 'Exemplo exemplo', 'autor_id' => 2, 'publicado_em' => '2011-04-21 16:42:05', 'autorizado_em' => '2011-04-21']);
     $noticia->set("autorizado_em", $autorizadoEm ?: "22/03/2015");
     $noticia->set("publicado_em", $publicadoEm ?: "25/03/2015 16:42:05");
     $this->Noticias->save($noticia);
     $this->assertEmpty($noticia->errors());
     return $noticia;
 }
Пример #6
0
 /**
  * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key
  *
  * @return void
  */
 public function testSaveReplaceSaveStrategyAdding()
 {
     $articles = new Table(['table' => 'articles', 'alias' => 'Articles', 'connection' => $this->connection, 'entityClass' => 'Cake\\ORM\\Entity']);
     $articles->hasMany('Comments', ['saveStrategy' => 'replace']);
     $article = $articles->newEntity(['title' => 'Bakeries are sky rocketing', 'body' => 'All because of cake', 'comments' => [['user_id' => 1, 'comment' => 'That is true!'], ['user_id' => 2, 'comment' => 'Of course']]], ['associated' => ['Comments']]);
     $article = $articles->save($article, ['associated' => ['Comments']]);
     $commentId = $article->comments[0]->id;
     $sizeComments = count($article->comments);
     $articleId = $article->id;
     $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
     $this->assertTrue($articles->Comments->exists(['id' => $commentId]));
     unset($article->comments[0]);
     $article->comments[] = $articles->Comments->newEntity(['user_id' => 1, 'comment' => 'new comment']);
     $article->dirty('comments', true);
     $article = $articles->save($article, ['associated' => ['Comments']]);
     $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
     $this->assertFalse($articles->Comments->exists(['id' => $commentId]));
     $this->assertTrue($articles->Comments->exists(['to_char(comment)' => 'new comment', 'article_id' => $articleId]));
 }
Пример #7
0
 /**
  * Helper function called on write for database sessions.
  *
  * @param int $id ID that uniquely identifies session in database
  * @param mixed $data The value of the data to be saved.
  * @return bool True for successful write, false otherwise.
  */
 public function write($id, $data)
 {
     if (!$id) {
         return false;
     }
     $expires = time() + $this->_timeout;
     $record = compact('data', 'expires');
     $record[$this->_table->primaryKey()] = $id;
     $result = $this->_table->save(new Entity($record));
     return (bool) $result;
 }
Пример #8
0
 /**
  * Find or create new draft database entry and return entity ID
  * 
  * @param \Cake\ORM\Table $table      Table instance
  * @param array|null      $conditions Find conditions
  *
  * @return int             $id         Draft Id
  */
 public function getDraftId(Table $table, $conditions = [])
 {
     $conditions = array_merge($this->config[$table->alias()]['conditions'], $conditions);
     $result = $table->find()->select(['id' => $table->primaryKey()])->andWhere($conditions)->first();
     if ($result) {
         return $result->id;
     } else {
         $entity = $table->newEntity($conditions, ['validate' => false]);
         $entity = $table->save($entity);
         return $entity->id;
     }
 }
Пример #9
0
 /**
  * Toggle field value.
  *
  * @param Table|\Cake\ORM\Table $table
  * @param string|int $id
  * @param string|int $value
  * @param string $field
  * @throw BadRequestException
  * @throw RuntimeException
  */
 public function fieldToggle($table, $id, $value, $field = self::TOGGLE_DEFAULT_FIELD)
 {
     $this->_checkIsAjax();
     $this->_checkToggleData($id, $value);
     $this->_controller->viewBuilder()->layout('ajax')->templatePath('Common');
     $entity = $table->get($id);
     $entity->{$field} = !(int) $value;
     if ($result = $table->save($entity)) {
         $this->_controller->set('record', $result);
         $this->_controller->render('toggle');
     } else {
         throw new RuntimeException(__d('union', 'Failed toggling field {0} to {1}', $field, $entity->{$field}));
     }
 }
Пример #10
0
    /**
     * - One
     * -- One-SubA
     * - Two
     * -- Two-SubA
     * --- Two-SubA-1
     * ---- Two-SubA-1-1
     * -- Two-SubB
     * -- Two-SubC
     * - Three
     * - Four
     * -- Four-SubA
     *
     * @return void
     */
    public function testGenerateWithAutoPathAndHideUnrelatedAndSiblings()
    {
        $this->skipIf(true, 'FIXME');
        $data = [['name' => 'Two-SubB', 'parent_id' => 2], ['name' => 'Two-SubC', 'parent_id' => 2]];
        foreach ($data as $row) {
            $row = new Entity($row);
            $this->Table->save($row);
        }
        $tree = $this->Table->find('threaded')->toArray();
        $id = 6;
        $nodes = $this->Table->find('path', ['for' => $id]);
        $path = $nodes->extract('id')->toArray();
        $output = $this->Tree->generate($tree, ['autoPath' => [6, 11], 'hideUnrelated' => true, 'treePath' => $path, 'callback' => [$this, '_myCallbackSiblings']]);
        // Two-SubA
        //debug($output);
        $expected = <<<TEXT

<ul>
\t<li>One (sibling)</li>
\t<li class="active">Two (active)
\t<ul>
\t\t<li class="active">Two-SubA (active)
\t\t<ul>
\t\t\t<li>Two-SubA-1</li>
\t\t</ul>
\t\t</li>
\t\t<li>Two-SubB</li>
\t\t<li>Two-SubC</li>
\t</ul>
\t</li>
\t<li>Three (sibling)</li>
\t<li>Four (sibling)</li>
</ul>

TEXT;
        $output = str_replace(["\t", "\r", "\n"], '', $output);
        $expected = str_replace(["\t", "\r", "\n"], '', $expected);
        //debug($output);
        //debug($expected);
        $this->assertTextEquals($expected, $output);
    }
Пример #11
0
 /**
  * Helper function containing the actual code for removeFromTree
  *
  * @param \Cake\ORM\Entity $node The node to remove from the tree
  * @return \Cake\ORM\Entity|false the node after being removed from the tree or
  * false on error
  */
 protected function _removeFromTree($node)
 {
     $config = $this->config();
     $left = $node->get($config['left']);
     $right = $node->get($config['right']);
     $parent = $node->get($config['parent']);
     $node->set($config['parent'], null);
     if ($right - $left == 1) {
         return $this->_table->save($node);
     }
     $primary = $this->_table->primaryKey();
     $this->_table->updateAll([$config['parent'] => $parent], [$config['parent'] => $node->get($primary)]);
     $this->_sync(1, '-', 'BETWEEN ' . ($left + 1) . ' AND ' . ($right - 1));
     $this->_sync(2, '-', "> {$right}");
     $edge = $this->_getMax();
     $node->set($config['left'], $edge + 1);
     $node->set($config['right'], $edge + 2);
     $fields = [$config['parent'], $config['left'], $config['right']];
     $this->_table->updateAll($node->extract($fields), [$primary => $node->get($primary)]);
     foreach ($fields as $field) {
         $node->dirty($field, false);
     }
     return $node;
 }
Пример #12
0
 /**
  * Integration test for replacing entities with HasMany and no already persisted entities. The transaction must be successfull.
  * Replace operation should prevent considering 0 changed records an error when they are not found in the table
  *
  * @return void
  */
 public function testReplaceHasManyNoPersistedEntities()
 {
     $authors = new Table(['connection' => $this->connection, 'alias' => 'Authors', 'table' => 'authors']);
     $authors->hasMany('Articles');
     $author = $authors->newEntity(['name' => 'mylux']);
     $author = $authors->save($author);
     $newArticles = $authors->Articles->newEntities([['title' => 'New bakery next corner', 'body' => 'They sell tastefull cakes'], ['title' => 'Spicy cake recipe', 'body' => 'chocolate and peppers']]);
     $authors->Articles->deleteAll(['1=1']);
     $sizeArticles = count($newArticles);
     $this->assertTrue($authors->Articles->link($author, $newArticles));
     $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
     $this->assertEquals(count($author->articles), $sizeArticles);
     $this->assertTrue($authors->Articles->replace($author, $newArticles));
     $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
 }
Пример #13
0
 /**
  * Processes the records.
  *
  * @param \Cake\ORM\Table $table
  * @param int $chunkCount
  * @param int $chunkSize
  * @return void
  */
 protected function _process(Table $table, $chunkCount, $chunkSize)
 {
     $query = $table->find();
     if ($table->hasFinder('purifier')) {
         $query->find('purifier');
     }
     $fields = explode(',', $this->param('fields'));
     $fields[] = $table->primaryKey();
     $results = $query->select($fields)->offset($chunkCount)->limit($chunkSize)->orderDesc($table->aliasField($table->primaryKey()))->all();
     if (empty($results)) {
         return;
     }
     foreach ($results as $result) {
         try {
             $table->save($result);
             $chunkCount++;
         } catch (\Exception $e) {
             $this->error($e->getMessage());
         }
     }
 }
 /**
  * Helper function to import a set of records for a single Table.
  *
  * Used by imporTables().
  *
  * @param Cake\ORM\Table $Table A Table instance to save records into.
  * @param array $records An array of Entity records to save into the Table.
  * @return void
  */
 public function importTable(Table $Table, $records)
 {
     foreach ($records as $record) {
         $result = $Table->save($record);
         $key = $this->findKey($Table, $record);
         if ($result) {
             $this->out("{$Table->alias()} ({$key}): Save successful.");
         } else {
             $this->out("{$Table->alias()} ({$key}): <warning>Save failed.</warning>");
         }
     }
 }
Пример #15
0
 /**
  * Save record data in database.
  *
  * @param EntityInterface $entity
  * @param array $options
  * @return bool|EntityInterface|mixed|\Union\Core\ORM\Entity
  */
 public function save(EntityInterface $entity, $options = [])
 {
     return parent::save($entity, $options);
 }
Пример #16
0
 /**
  * {@inheritDoc}
  *
  * Additional options
  * - 'strict': Throw exception instead of returning false. Defaults to false.
  */
 public function save(EntityInterface $entity, $options = [])
 {
     if ($options instanceof SaveOptionsBuilder) {
         $options = $options->toArray();
     }
     $options += ['strict' => false];
     $result = parent::save($entity, $options);
     if ($result === false && $options['strict'] === true) {
         throw new InvalidArgumentException('Could not save: ' . print_r($entity->errors(), true));
     }
     return $result;
 }
Пример #17
0
 /**
  * Helper function to import a set of records for a single Table.
  *
  * Used by imporTables().
  *
  * @param Cake\ORM\Table $Table A Table instance to save records into.
  * @param array|\Generator $records An array of Entity records to save into the Table.
  * @param array $options Options to pass to save().
  * @return void
  */
 public function importTable(Table $Table, $records, array $options = [])
 {
     $defaultOptions = ['checkRules' => true, 'checkExisting' => true];
     $options = $options + $defaultOptions;
     foreach ($records as $record) {
         $action = $record->isNew() ? 'Create' : 'Update';
         $result = $Table->save($record, $options);
         $key = $this->findKey($Table, $record);
         if ($result) {
             $this->verbose("<success>{$Table->alias()} ({$key}): {$action} successful.</success>");
         } else {
             $this->quiet("<warning>{$Table->alias()} ({$key}): {$action} failed.</warning>");
             $this->printValidationErrors($Table->alias(), $this->findKey($Table, $record), $record->errors());
         }
     }
 }
 /**
  * saveX
  *
  * @author Rafael Armenio <*****@*****.**>
  */
 public function saveX(EntityInterface $entity, $options = array())
 {
     $cacheTag = sprintf('table_%s', $this->table());
     $cache = $this->getCache();
     $cache->clearByTags(array($cacheTag));
     return parent::save($entity, $options);
 }
Пример #19
-1
 /**
  * Toggle ajax field.
  *
  * @param Table $table
  * @param $id
  * @param $value
  * @param string $field
  */
 public function fieldToggle(Table $table, $id, $value, $field = 'status')
 {
     $this->_controller->serializeAjax = false;
     if (empty($id) || $value === null) {
         throw new Exception(__d('union', 'Invalid content'));
     }
     $this->_controller->viewBuilder()->layout('ajax')->templatePath('Common');
     $record = $table->get($id);
     $record->{$field} = (int) (!$value);
     if ($entity = $table->save($record)) {
         $this->_controller->set('record', $entity);
         $this->_controller->render('Union/Core.toggle');
     } else {
         throw new Exception(__d('union', 'Failed toggling field {0} to {1}', $field, $record->{$field}));
     }
 }