本文整理汇总了PHP中Drupal\Core\Entity\EntityStorageInterface::create方法的典型用法代码示例。如果您正苦于以下问题:PHP EntityStorageInterface::create方法的具体用法?PHP EntityStorageInterface::create怎么用?PHP EntityStorageInterface::create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Core\Entity\EntityStorageInterface
的用法示例。
在下文中一共展示了EntityStorageInterface::create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testConfigurableEventHandler
/**
* Tests ConfigurableEventHandlerEntityBundle.
*
* Test that rules are triggered correctly based upon the fully qualified
* event name as well as the base event name.
*
* @todo Add integrity check that node.field_integer is detected by Rules.
*/
public function testConfigurableEventHandler()
{
// Create rule1 with the 'rules_entity_presave:node--page' event.
$rule1 = $this->expressionManager->createRule();
$rule1->addAction('rules_test_log', ContextConfig::create()->map('message', 'node.field_integer.0.value'));
$config_entity1 = $this->storage->create(['id' => 'test_rule1']);
$config_entity1->set('events', [['event_name' => 'rules_entity_presave:node--page']]);
$config_entity1->set('expression', $rule1->getConfiguration());
$config_entity1->save();
// Create rule2 with the 'rules_entity_presave:node' event.
$rule2 = $this->expressionManager->createRule();
$rule2->addAction('rules_test_log', ContextConfig::create()->map('message', 'node.field_integer.1.value'));
$config_entity2 = $this->storage->create(['id' => 'test_rule2']);
$config_entity2->set('events', [['event_name' => 'rules_entity_presave:node']]);
$config_entity2->set('expression', $rule2->getConfiguration());
$config_entity2->save();
// The logger instance has changed, refresh it.
$this->logger = $this->container->get('logger.channel.rules');
// Add node.field_integer.0.value to rules log message, read result.
$this->node->field_integer->setValue(['0' => 11, '1' => 22]);
// Trigger node save.
$entity_type_id = $this->node->getEntityTypeId();
$event = new EntityEvent($this->node, [$entity_type_id => $this->node]);
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch("rules_entity_presave:{$entity_type_id}", $event);
// Test that the action in the rule1 logged node value.
$this->assertRulesLogEntryExists(11, 1);
// Test that the action in the rule2 logged node value.
$this->assertRulesLogEntryExists(22, 0);
}
示例2: view
/**
* {@inheritdoc}
*/
public function view(EntityInterface $entity, $view_mode = 'full', $langcode = NULL)
{
$message = $this->contactMessageStorage->create(['contact_form' => $entity->id()]);
$form = $this->entityFormBuilder->getForm($message);
$form['#title'] = $entity->label();
$form['#cache']['contexts'][] = 'user.permissions';
$this->renderer->addCacheableDependency($form, $this->config);
return $form;
}
示例3: addForm
/**
* Presents the custom block creation form.
*
* @param \Drupal\block_content\BlockContentTypeInterface $block_content_type
* The custom block type to add.
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request object.
*
* @return array
* A form array as expected by drupal_render().
*/
public function addForm(BlockContentTypeInterface $block_content_type, Request $request)
{
$block = $this->blockContentStorage->create(array('type' => $block_content_type->id()));
if (($theme = $request->query->get('theme')) && in_array($theme, array_keys(list_themes()))) {
// We have navigated to this page from the block library and will keep track
// of the theme for redirecting the user to the configuration page for the
// newly created block in the given theme.
$block->setTheme($theme);
}
return $this->entityFormBuilder()->getForm($block);
}
示例4: testContextDefinitionExport
/**
* Make sure that expressions using context definitions can be exported.
*/
public function testContextDefinitionExport()
{
$rule = $this->expressionManager->createRule(['context_definitions' => ['test' => ContextDefinition::create('string')->setLabel('Test string')->toArray()]]);
$config_entity = $this->storage->create(['id' => 'test_rule'])->setExpression($rule);
$config_entity->save();
$loaded_entity = $this->storage->load('test_rule');
// Create the Rules expression object from the configuration.
$expression = $loaded_entity->getExpression();
$context_definitions = $expression->getContextDefinitions();
$this->assertEqual($context_definitions['test']->getDataType(), 'string', 'Data type of context definition is correct.');
$this->assertEqual($context_definitions['test']->getLabel(), 'Test string', 'Label of context definition is correct.');
}
示例5: testContextDefinitionExport
/**
* Make sure that expressions using context definitions can be exported.
*/
public function testContextDefinitionExport()
{
$component = RulesComponent::create($this->expressionManager->createRule())->addContextDefinition('test', ContextDefinition::create('string')->setLabel('Test string'));
$config_entity = $this->storage->create(['id' => 'test_rule'])->updateFromComponent($component);
$config_entity->save();
$loaded_entity = $this->storage->load('test_rule');
// Create the Rules expression object from the configuration.
$expression = $loaded_entity->getExpression();
$this->assertInstanceOf(Rule::class, $expression);
$context_definitions = $loaded_entity->getContextDefinitions();
$this->assertEquals($context_definitions['test']->getDataType(), 'string', 'Data type of context definition is correct.');
$this->assertEquals($context_definitions['test']->getLabel(), 'Test string', 'Label of context definition is correct.');
}
示例6: import
/**
* {@inheritdoc}
*/
public function import($currencyCode) {
if ($existingEntity = $this->storage->load($currencyCode)) {
// Pretend the currency was just imported.
return $existingEntity;
}
$defaultLangcode = $this->languageManager->getDefaultLanguage()->getId();
$currency = $this->externalRepository->get($currencyCode, $defaultLangcode, 'en');
$values = [
'langcode' => $defaultLangcode,
'currencyCode' => $currency->getCurrencyCode(),
'name' => $currency->getName(),
'numericCode' => $currency->getNumericCode(),
'symbol' => $currency->getSymbol(),
'fractionDigits' => $currency->getFractionDigits(),
];
$entity = $this->storage->create($values);
$entity->trustData()->save();
if ($this->languageManager->isMultilingual()) {
// Import translations for any additional languages the site has.
$languages = $this->languageManager->getLanguages(LanguageInterface::STATE_CONFIGURABLE);
$languages = array_diff_key($languages, [$defaultLangcode => $defaultLangcode]);
$langcodes = array_map(function ($language) {
return $language->getId();
}, $languages);
$this->importEntityTranslations($entity, $langcodes);
}
return $entity;
}
示例7: view
/**
* {@inheritdoc}
*/
public function view(EntityInterface $entity, $view_mode = 'full', $langcode = NULL) {
if ($entity->status()) {
$message = $this->contactMessageStorage->create([
'contact_form' => $entity->id(),
]);
$form = $this->entityFormBuilder->getForm($message);
$form['#title'] = $entity->label();
$form['#cache']['contexts'][] = 'user.permissions';
$this->renderer->addCacheableDependency($form, $this->config);
}
else {
// Form disabled, display a custom message using a template.
$form['disabled_form_error'] = array(
'#theme' => 'contact_storage_disabled_form',
'#contact_form' => $entity,
'#redirect_uri' => $entity->getThirdPartySetting('contact_storage', 'redirect_uri', ''),
'#disabled_form_message' => $entity->getThirdPartySetting('contact_storage', 'disabled_form_message', t('This contact form has been disabled.')),
);
}
// Add required cacheability metadata from the contact form entity, so that
// changing it invalidates the cache.
$this->renderer->addCacheableDependency($form, $entity);
return $form;
}
示例8: getTestFile
/**
* Creates and gets test image file.
*
* @return \Drupal\file\FileInterface
* File object.
*/
protected function getTestFile() {
file_unmanaged_copy(drupal_get_path('module', 'crop') . '/tests/files/sarajevo.png', PublicStream::basePath());
return $this->fileStorage->create([
'uri' => 'public://sarajevo.png',
'status' => FILE_STATUS_PERMANENT,
]);
}
示例9: loadMultiple
/**
* {@inheritdoc}
*/
public function loadMultiple(EntityStorageInterface $storage, array $sub_ids = NULL)
{
if (isset($this->configuration['bundle_migration'])) {
/** @var \Drupal\migrate\Entity\MigrationInterface $bundle_migration */
$bundle_migration = $storage->load($this->configuration['bundle_migration']);
$source_id = array_keys($bundle_migration->getSourcePlugin()->getIds())[0];
$this->bundles = array();
foreach ($bundle_migration->getSourcePlugin()->getIterator() as $row) {
$this->bundles[] = $row[$source_id];
}
} else {
// This entity type has no bundles ('user', 'feed', etc).
$this->bundles = array($this->migration->getSourcePlugin()->entityTypeId());
}
$sub_ids_to_load = isset($sub_ids) ? array_intersect($this->bundles, $sub_ids) : $this->bundles;
$migrations = array();
foreach ($sub_ids_to_load as $id) {
$values = $this->migration->toArray();
$values['id'] = $this->migration->id() . ':' . $id;
$values['source']['bundle'] = $id;
/** @var \Drupal\migrate_drupal\Entity\MigrationInterface $migration */
$migration = $storage->create($values);
if ($migration->getSourcePlugin()->checkRequirements()) {
$fields = array_keys($migration->getSourcePlugin()->fields());
$migration->process += array_combine($fields, $fields);
$migrations[$migration->id()] = $migration;
}
}
return $migrations;
}
示例10: createCart
/**
* {@inheritdoc}
*/
public function createCart($orderType, StoreInterface $store, AccountInterface $account = NULL) {
$account = $account ?: $this->currentUser;
$uid = $account->id();
$storeId = $store->id();
if ($this->getCartId($orderType, $store, $account)) {
// Don't allow multiple cart orders matching the same criteria.
throw new DuplicateCartException("A cart order for type '$orderType', store '$storeId' and account '$uid' already exists.");
}
// Create the new cart order.
$cart = $this->orderStorage->create([
'type' => $orderType,
'store_id' => $storeId,
'uid' => $uid,
'cart' => TRUE,
]);
$cart->save();
// Store the new cart order id in the anonymous user's session so that it
// can be retrieved on the next page load.
if ($account->isAnonymous()) {
$this->cartSession->addCartId($cart->id());
}
// Cart data has already been loaded, add the new cart order to the list.
if (isset($this->cartData[$uid])) {
$this->cartData[$uid][$cart->id()] = [
'type' => $orderType,
'store_id' => $storeId,
];
}
return $cart;
}
示例11: loadMultiple
/**
* {@inheritdoc}
*/
public function loadMultiple(EntityStorageInterface $storage, array $sub_ids = NULL)
{
/** @var \Drupal\migrate\Entity\MigrationInterface $bundle_migration */
$bundle_migration = $storage->load('d6_taxonomy_vocabulary');
$migrate_executable = new MigrateExecutable($bundle_migration, new MigrateMessage());
$process = array_intersect_key($bundle_migration->get('process'), $bundle_migration->getDestinationPlugin()->getIds());
$migrations = array();
$vid_map = array();
foreach ($bundle_migration->getIdMap() as $key => $value) {
$old_vid = unserialize($key)['sourceid1'];
$new_vid = $value['destid1'];
$vid_map[$old_vid] = $new_vid;
}
foreach ($bundle_migration->getSourcePlugin()->getIterator() as $source_row) {
$row = new Row($source_row, $source_row);
$migrate_executable->processRow($row, $process);
$old_vid = $source_row['vid'];
$new_vid = $row->getDestinationProperty('vid');
$vid_map[$old_vid] = $new_vid;
}
foreach ($vid_map as $old_vid => $new_vid) {
$values = $this->migration->toArray();
$migration_id = $this->migration->id() . ':' . $old_vid;
$values['id'] = $migration_id;
$values['source']['vid'] = $old_vid;
$values['process'][$new_vid] = 'tid';
$migrations[$migration_id] = $storage->create($values);
}
return $migrations;
}
示例12: generateElements
/**
* {@inheritdoc}
*/
protected function generateElements(array $values)
{
$num = $values['num'];
$kill = $values['kill'];
$pass = $values['pass'];
$age = $values['time_range'];
$roles = array_filter($values['roles']);
if ($kill) {
$uids = $this->userStorage->getQuery()->condition('uid', 1, '>')->execute();
$users = $this->userStorage->loadMultiple($uids);
$this->userStorage->delete($users);
$this->setMessage($this->formatPlural(count($uids), '1 user deleted', '@count users deleted.'));
}
if ($num > 0) {
$names = array();
while (count($names) < $num) {
$name = $this->getRandom()->word(mt_rand(6, 12));
$names[$name] = '';
}
if (empty($roles)) {
$roles = array(DRUPAL_AUTHENTICATED_RID);
}
foreach ($names as $name => $value) {
$account = $this->userStorage->create(array('uid' => NULL, 'name' => $name, 'pass' => $pass, 'mail' => $name . '@example.com', 'status' => 1, 'created' => REQUEST_TIME - mt_rand(0, $age), 'roles' => array_values($roles), 'devel_generate' => TRUE));
// Populate all fields with sample values.
$this->populateFields($account);
$account->save();
}
}
$this->setMessage($this->t('@num_users created.', array('@num_users' => $this->formatPlural($num, '1 user', '@count users'))));
}
示例13: importTaxRateAmount
/**
* Imports a single tax rate amount.
*
* @param \CommerceGuys\Tax\Model\TaxRateAmountInterface $taxRateAmount
* The tax rate amount to import.
*/
protected function importTaxRateAmount(ExternalTaxRateAmountInterface $taxRateAmount)
{
$startDate = $taxRateAmount->getStartDate() ? $taxRateAmount->getStartDate()->getTimestamp() : NULL;
$endDate = $taxRateAmount->getEndDate() ? $taxRateAmount->getEndDate()->getTimestamp() : NULL;
$values = ['rate' => $taxRateAmount->getRate()->getId(), 'id' => $taxRateAmount->getId(), 'amount' => $taxRateAmount->getAmount(), 'startDate' => $startDate, 'endDate' => $endDate];
return $this->taxRateAmountStorage->create($values);
}
示例14: testUserLogoutEvent
/**
* Test that the user logout hook triggers the Rules event listener.
*/
public function testUserLogoutEvent()
{
$rule = $this->expressionManager->createInstance('rules_reaction_rule', ['event' => 'rules_user_logout']);
$rule->addCondition('rules_test_true');
$rule->addAction('rules_test_log');
$config_entity = $this->storage->create(['id' => 'test_rule', 'expression_id' => 'rules_reaction_rule', 'event' => 'rules_user_logout', 'configuration' => $rule->getConfiguration()]);
$config_entity->save();
// Rebuild the container so that the newly configured event gets picked up.
$this->container->get('kernel')->rebuildContainer();
// The logger instance has changed, refresh it.
$this->logger = $this->container->get('logger.channel.rules');
$account = $this->container->get('current_user');
// Invoke the hook manually which should trigger the rule.
rules_user_logout($account);
// Test that the action in the rule logged something.
$this->assertRulesLogEntryExists('action called');
}
示例15: newEntity
/**
* {@inheritdoc}
*/
protected function newEntity(FeedInterface $feed)
{
$values = $this->configuration['values'];
$entity = $this->storageController->create($values);
$entity->enforceIsNew();
if ($entity instanceof EntityOwnerInterface) {
$entity->setOwnerId($this->configuration['owner_id']);
}
return $entity;
}