本文整理汇总了PHP中Cake\ORM\Table::newEntity方法的典型用法代码示例。如果您正苦于以下问题:PHP Table::newEntity方法的具体用法?PHP Table::newEntity怎么用?PHP Table::newEntity使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cake\ORM\Table
的用法示例。
在下文中一共展示了Table::newEntity方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: entityGenerator
/**
* 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);
}
}
示例2: testFind
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);
}
}
示例3: upsertCronPostAction
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');
}
示例4: buildMarshalMap
/**
* 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;
}];
}
示例5: __preparaNoticia
/**
*
* @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: testSave
/**
* 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"));
}
示例7: newEntity
/**
* 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);
}
示例8: getDraftId
/**
* 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: groupVersions
/**
* 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;
});
}
示例10: testSaveReplaceSaveStrategyAdding
/**
* 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]));
}
示例11: changePassword
/**
* 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);
}
示例12: beforeSave
/**
* 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);
}
示例13: testReplaceHasManyNoPersistedEntities
/**
* 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));
}
示例14: entityGenerator
/**
* 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);
}
}