newEntity() public method

By default all the associations on this table will be hydrated. You can limit which associations are built, or include deeper associations using the options parameter: $article = $this->Articles->newEntity( $this->request->data(), ['associated' => ['Tags', 'Comments.Users']] ); You can limit fields that will be present in the constructed entity by passing the fieldList option, which is also accepted for associations: $article = $this->Articles->newEntity($this->request->data(), [ 'fieldList' => ['title', 'body', 'tags', 'comments'], 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']] ] ); The fieldList option lets remove or restrict input data from ending up in the entity. If you'd like to relax the entity's default accessible fields, you can use the accessibleFields option: $article = $this->Articles->newEntity( $this->request->data(), ['accessibleFields' => ['protected_field' => true]] ); By default, the data is validated before being passed to the new entity. In the case of invalid fields, those will not be present in the resulting object. The validate option can be used to disable validation on the passed data: $article = $this->Articles->newEntity( $this->request->data(), ['validate' => false] ); You can also pass the name of the validator to use in the validate option. If null is passed to the first param of this function, no validation will be performed. You can use the Model.beforeMarshal event to modify request data before it is converted into entities.
public newEntity ( $data = null, array $options = [] )
$options array
 /**
  * Helper generator for use with importTable().
  *
  * Yields a single new Entity instance approciate for $Table for each
  * of $records where the values are merged with $defaults.
  *
  * Will skip any records that fail to validate, dumping validation
  * errors to the console in the process.
  *
  * 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.
  * @param array $defaults Optional array of default field values to merge into each record.
  * @param array $options Optional array of newEntity() options to use.
  * @return void
  */
 public function entityGenerator(Table $Table, array $records, array $defaults = [], array $options = [])
 {
     $defaultOptions = ['validate' => true, 'accessibleFields' => ['*' => true]];
     $options = $options + $defaultOptions;
     $keyField = $Table->primaryKey();
     foreach ($records as $r) {
         $r = Hash::merge($defaults, $r);
         $id = !empty($r[$keyField]) ? $r[$keyField] : false;
         if ($id) {
             $entity = $Table->find()->where([$keyField => $id])->first();
             if ($entity) {
                 $entity = $Table->patchEntity($entity, $r, $options);
                 if (!$entity->dirty()) {
                     $this->verbose("<success>{$Table->alias()} ({$id}): No changes.</success>");
                     continue;
                 }
             } else {
                 $entity = $Table->newEntity($r, $options);
                 $entity->isNew(true);
             }
         } else {
             $entity = $Table->newEntity($r, $options);
         }
         $errors = $entity->errors();
         if ($errors) {
             $this->printValidationErrors($Table->alias(), $id, $errors);
             continue;
         }
         (yield $entity);
     }
 }
 public function testFind()
 {
     $entities = [];
     foreach ($this->entityMap as $discriminator => $class) {
         $data = ['discriminator' => $discriminator];
         $entities[] = $this->table->newEntity($data);
     }
     $this->table->saveMany($entities);
     $found = $this->table->find()->toArray();
     $this->assertCount(6, $found);
     foreach ($found as $entity) {
         $class = $this->entityMap[$entity->discriminator];
         $this->assertInstanceOf($class, $entity);
     }
 }
Esempio n. 3
0
 public function upsertCronPostAction()
 {
     $id = $_POST['id'] ?? null;
     unset($_POST['id']);
     $cron = $id ? $this->cronsTable->get($id)->set($_POST) : $this->cronsTable->newEntity($_POST);
     if ($cron->dirty()) {
         try {
             $this->cronsTable->save($cron);
             $this->flasher->success("Success!");
         } catch (\Exception $e) {
             $this->flasher->error('Something went wrong while ' . ($cron->id ? 'updating' : 'creating') . ' the cron - ' . $e->getMessage());
         }
     }
     $this->redirect('/admin/crons');
 }
Esempio n. 4
0
 /**
  * Add in _translations marshalling handlers if translation marshalling is
  * enabled. You need to specifically enable translation marshalling by adding
  * `'translations' => true` to the options provided to `Table::newEntity()` or `Table::patchEntity()`.
  *
  * {@inheritDoc}
  */
 public function buildMarshalMap($marshaller, $map, $options)
 {
     if (isset($options['translations']) && !$options['translations']) {
         return [];
     }
     return ['_translations' => function ($value, $entity) use($marshaller, $options) {
         $translations = $entity->get('_translations');
         foreach ($this->_config['fields'] as $field) {
             $options['validate'] = $this->_config['validator'];
             $errors = [];
             if (!is_array($value)) {
                 return;
             }
             foreach ($value as $language => $fields) {
                 if (!isset($translations[$language])) {
                     $translations[$language] = $this->_table->newEntity();
                 }
                 $marshaller->merge($translations[$language], $fields, $options);
                 if ((bool) $translations[$language]->errors()) {
                     $errors[$language] = $translations[$language]->errors();
                 }
             }
             // Set errors into the root entity, so validation errors
             // match the original form data position.
             $entity->errors($errors);
         }
         return $translations;
     }];
 }
 /**
  *
  * @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;
 }
 /**
  * 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"));
 }
Esempio n. 7
0
 /**
  * Todo: doc bloc
  */
 public function newEntity($data = null, array $options = [])
 {
     if ($data === null && isset($options['gateway'])) {
         $gateway = Inflector::classify($options['gateway']);
         $chargeClass = '\\Payments\\Model\\Entity\\' . $gateway . 'Charge';
         $entity = new $chargeClass([], ['source' => $this->registryAlias()]);
         return $entity;
     }
     return parent::newEntity($data, $options);
 }
Esempio n. 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;
     }
 }
 /**
  * Modifies the results from a table find in order to merge full version records
  * into each entity under the `_versions` key
  *
  * @param \Cake\Datasource\ResultSetInterface $results Results to modify.
  * @return \Cake\Collection\Collection
  */
 public function groupVersions($results)
 {
     return $results->map(function ($row) {
         $versions = (array) $row->get('__version');
         $grouped = new Collection($versions);
         $result = [];
         foreach ($grouped->combine('field', 'content', 'version_id') as $versionId => $keys) {
             $version = $this->_table->newEntity($keys + ['version_id' => $versionId], ['markNew' => false, 'useSetters' => false, 'markClean' => true]);
             $result[$versionId] = $version;
         }
         $options = ['setter' => false, 'guard' => false];
         $row->set('_versions', $result, $options);
         unset($row['__version']);
         $row->clean();
         return $row;
     });
 }
Esempio n. 10
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]));
 }
 /**
  * Let the logged in user change his password.
  *
  * @param array $options
  * @return void
  */
 public function changePassword($options = [])
 {
     $options = Hash::merge($this->_defaultConfig['changePassword'], $options);
     $entity = $this->UserTable->newEntity();
     $entity->accessible(['id', 'old_password', 'new_password', 'confirm_password'], true);
     if ($this->request->is(['post', 'put'])) {
         $entity = $this->UserTable->patchEntity($entity, $this->request->data);
         $entity->id = $this->_controller->Auth->user('id');
         $entity->isNew(false);
         if ($this->UserTable->changePassword($entity)) {
             $this->request->data = [];
             $entity = $this->UserTable->newEntity();
             $entity->id = $this->_controller->Auth->user('id');
             $entity->isNew(false);
             $this->handleFlashAndRedirect('success', $options);
         } else {
             $this->handleFlashAndRedirect('error', $options);
         }
     }
     $this->_controller->set('entity', $entity);
 }
Esempio n. 12
0
 /**
  * Implementation of the beforeSave event, handles uploading / saving and overwriting of image records.
  *
  * @param Event $event Event object.
  * @param Entity $entity Entity object.
  * @param \ArrayObject $options Options array.
  * @return void
  */
 public function beforeSave(Event $event, Entity $entity, \ArrayObject $options)
 {
     $fields = $this->config('fields');
     $alias = $this->_table->alias();
     $options['associated'] = [$this->_imagesTable->alias() => ['validate' => false]] + $options['associated'];
     $entities = [];
     foreach ($fields as $fieldName => $fieldType) {
         $uploadedImages = [];
         $field = $entity->get($fieldName);
         $field = $fieldType == 'one' ? [$field] : $field;
         foreach ($field as $image) {
             $result = array();
             if (!empty($image['tmp_name'])) {
                 $result = $this->_upload($image['name'], $image['tmp_name'], false);
             } elseif (is_string($image)) {
                 $result = $this->_upload($image, $image, true);
             }
             if (!empty($result)) {
                 $uploadedImages[] = $result + ['model' => $alias, 'field' => $fieldName];
             }
         }
         if (!empty($uploadedImages)) {
             if (!$entity->isNew() && $fieldType == 'one') {
                 $preexisting = $this->_imagesTable->find()->where(['model' => $alias, 'field' => $fieldName, 'foreign_key' => $entity->id])->bufferResults(false);
                 foreach ($preexisting as $index => $image) {
                     $this->_imagesTable->delete($image);
                 }
             }
             foreach ($uploadedImages as $image) {
                 $entities[] = $this->_imagesTable->newEntity($image);
             }
         }
         $entity->dirty($fieldName, true);
     }
     $entity->set('_images', $entities);
 }
Esempio n. 13
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));
 }
 /**
  * Helper generator for use with importTable().
  *
  * Yields a single new Entity instance approciate for $Table for each
  * of $records where the values are merged with $defaults.
  *
  * Will skip any records that fail to validate, dumping validation
  * errors to the console in the process.
  *
  * 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.
  * @param array $defaults Optional array of default field values to merge into each record.
  * @param array $options Optional array of newEntity() options to use.
  * @return void
  */
 public function entityGenerator(Table $Table, array $records, array $defaults = [], array $options = [])
 {
     $defaultOptions = ['validate' => true];
     $options = $options + $defaultOptions;
     foreach ($records as $i => $r) {
         $r = $Table->newEntity(Hash::merge($defaults, $r), $options);
         $errors = $r->errors();
         if ($errors) {
             $this->printValidationErrors($Table->alias(), $this->findKey($Table, $r), $errors);
             continue;
         }
         (yield $r);
     }
 }