本文整理汇总了PHP中Drupal\user\Entity\User::load方法的典型用法代码示例。如果您正苦于以下问题:PHP User::load方法的具体用法?PHP User::load怎么用?PHP User::load使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\user\Entity\User
的用法示例。
在下文中一共展示了User::load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: content
public function content()
{
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$userId = $user->get('uid')->value;
$data = array(array('job_title' => '', 'job_path' => '', 'company_name' => '', 'application_date' => ''));
$appliedJobs = db_select('user_job_application', 'uja')->condition('uja.user_id', $userId, '=')->fields('uja', array('job_id', 'date'))->orderBy('uja.date', 'DESC')->execute()->fetchAll();
if ($appliedJobs) {
$x = 0;
foreach ($appliedJobs as $appliedJob) {
$jobNode = \Drupal\node\Entity\Node::load($appliedJob->job_id);
$jobTitle = $jobNode->getTitle();
$jobPathAlias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $appliedJob->job_id);
$companyNodeEntity = $jobNode->get('field_company');
$companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id());
$companyName = $companyNode->getTitle();
$data[$x]['job_title'] = $jobTitle;
$data[$x]['job_path'] = $jobPathAlias;
$data[$x]['company_name'] = $companyName;
$data[$x]['application_date'] = $appliedJob->date;
$x++;
}
}
$markUp = $this->createMarkUp($data);
return array('#type' => 'markup', '#markup' => $markUp);
}
示例2: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
//TODO v2 Send Email via Cron not on Submit
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$username = $user->get('name')->value;
$userId = $user->get('uid')->value;
$mailManager = \Drupal::service('plugin.manager.mail');
$jobNode = \Drupal::routeMatch()->getParameter('node');
$jobNodeTitle = $jobNode->getTitle();
$companyNodeEntity = $jobNode->get('field_company');
$companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id());
$companyEmail = $companyNode->field_email->value;
$resumeFileId = $form_state->getValue('resume');
$resumeFile = db_select('file_managed', 'f')->condition('f.fid', $resumeFileId, '=')->fields('f', array('uri'))->execute()->fetchField();
$atttachment = array('filepath' => $resumeFile);
$module = 'job_mailer';
$key = 'apply_job';
$params['job_title'] = $jobNodeTitle;
$params['message'] = "<html>\n <p>Please see attached resume for user: {$username}\n </html>";
$params['attachment'] = $atttachment;
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$reply = \Drupal::config('system.site')->get('mail');
$result = $mailManager->mail($module, $key, $companyEmail, $langcode, $params, $reply, $send);
db_insert('user_job_application')->fields(array('job_id' => $jobNode->id(), 'user_id' => $userId, 'date' => date('Y-m-d H:i:s')))->execute();
drupal_set_message('Your application has been sent.');
}
示例3: setUp
/**
* Sets the test up.
*/
protected function setUp()
{
parent::setUp();
/** @var UserInterface $user */
$user = User::load(1);
// Create initial block.
$block = $this->createBlockContent('initial');
$blocks = array();
$logs = array();
// Get original block.
$blocks[] = $block->getRevisionId();
$logs[] = '';
// Create three revisions.
$revision_count = 3;
for ($i = 0; $i < $revision_count; $i++) {
$block->setNewRevision(TRUE);
$block->setRevisionLogMessage($this->randomMachineName(32));
$block->setRevisionUser($this->adminUser);
$block->setRevisionCreationTime(REQUEST_TIME);
$logs[] = $block->getRevisionLogMessage();
$block->save();
$blocks[] = $block->getRevisionId();
}
$this->blocks = $blocks;
$this->revisionLogs = $logs;
}
示例4: deleteAllUsers
public static function deleteAllUsers($roles = NULL)
{
$count = 0;
$db_connection = Database::getConnection();
if (!$roles) {
$result = $db_connection->query('SELECT uid FROM {users} WHERE uid > 1')->fetchAllAssoc('uid');
foreach ($result as $data) {
$user = User::load($data->uid);
$user->delete();
$count++;
}
// Delete the URL aliases
$db_connection->query("DELETE FROM {url_alias} WHERE source LIKE 'user/%%'");
} else {
if (is_array($roles)) {
$result = array();
foreach ($roles as $role) {
$result = array_merge($result, db_select('user__roles', 'roles_target_id')->fields('roles_target_id', array('entity_id'))->condition('roles_target_id', $role, '=')->execute()->fetchCol('entity_id'));
}
} else {
$result = db_select('user__roles', 'roles_target_id')->fields('roles_target_id', array('entity_id'))->condition('roles_target_id', $roles, '=')->execute()->fetchCol('entity_id');
}
foreach ($result as $data) {
$user = User::load($data);
$user->delete();
$count++;
}
// @TODO Delete individual aliases
}
return $count;
}
示例5: execute
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
$uid = $input->getArgument('user');
$user = User::load($uid);
if (!$user) {
$io->error(sprintf($this->trans('commands.user.password.reset.errors.invalid-user'), $uid));
return 1;
}
$password = $input->getArgument('password');
if (!$password) {
$io->error(sprintf($this->trans('commands.user.password.reset.errors.empty-password'), $uid));
return 1;
}
try {
$user->setPassword($password);
$user->save();
$schema = $this->database->schema();
$flood = $schema->findTables('flood');
if ($flood) {
$this - $this->chainQueue->addCommand('user:login:clear:attempts', ['uid' => $uid]);
}
} catch (\Exception $e) {
$io->error($e->getMessage());
return 1;
}
$io->success(sprintf($this->trans('commands.user.password.reset.messages.reset-successful'), $uid));
}
示例6: testExportWithReferences
/**
* Tests exportContentWithReferences().
*/
public function testExportWithReferences()
{
\Drupal::service('module_installer')->install(['node', 'default_content']);
\Drupal::service('router.builder')->rebuild();
$this->defaultContentManager = \Drupal::service('default_content.manager');
$user = User::create(['name' => 'my username']);
$user->save();
// Reload the user to get the proper casted values from the DB.
$user = User::load($user->id());
$node_type = NodeType::create(['type' => 'test']);
$node_type->save();
$node = Node::create(['type' => $node_type->id(), 'title' => 'test node', 'uid' => $user->id()]);
$node->save();
// Reload the node to get the proper casted values from the DB.
$node = Node::load($node->id());
/** @var \Symfony\Component\Serializer\Serializer $serializer */
$serializer = \Drupal::service('serializer');
\Drupal::service('rest.link_manager')->setLinkDomain(DefaultContentManager::LINK_DOMAIN);
$expected_node = $serializer->serialize($node, 'hal_json', ['json_encode_options' => JSON_PRETTY_PRINT]);
$expected_user = $serializer->serialize($user, 'hal_json', ['json_encode_options' => JSON_PRETTY_PRINT]);
$exported_by_entity_type = $this->defaultContentManager->exportContentWithReferences('node', $node->id());
// Ensure that the node type is not tryed to be exported.
$this->assertEqual(array_keys($exported_by_entity_type), ['node', 'user']);
// Ensure the right UUIDs are exported.
$this->assertEqual([$node->uuid()], array_keys($exported_by_entity_type['node']));
$this->assertEqual([$user->uuid()], array_keys($exported_by_entity_type['user']));
// Compare the actual serialized data.
$this->assertEqual(reset($exported_by_entity_type['node']), $expected_node);
$this->assertEqual(reset($exported_by_entity_type['user']), $expected_user);
}
示例7: testContactLink
/**
* Tests contact link.
*/
public function testContactLink()
{
$accounts = array();
$accounts['root'] = User::load(1);
// Create an account with access to all contact pages.
$admin_account = $this->drupalCreateUser(array('administer users'));
$accounts['admin'] = $admin_account;
// Create an account with no access to contact pages.
$no_contact_account = $this->drupalCreateUser();
$accounts['no_contact'] = $no_contact_account;
// Create an account with access to contact pages.
$contact_account = $this->drupalCreateUser(array('access user contact forms'));
$accounts['contact'] = $contact_account;
$this->drupalLogin($admin_account);
$this->drupalGet('test-contact-link');
// The admin user has access to all contact links beside his own.
$this->assertContactLinks($accounts, array('root', 'no_contact', 'contact'));
$this->drupalLogin($no_contact_account);
$this->drupalGet('test-contact-link');
// Ensure that the user without the permission doesn't see any link.
$this->assertContactLinks($accounts, array());
$this->drupalLogin($contact_account);
$this->drupalGet('test-contact-link');
$this->assertContactLinks($accounts, array('root', 'admin', 'no_contact'));
// Disable contact link for no_contact.
$this->userData->set('contact', $no_contact_account->id(), 'enabled', FALSE);
// @todo Remove cache invalidation in https://www.drupal.org/node/2477903.
Cache::invalidateTags($no_contact_account->getCacheTagsToInvalidate());
$this->drupalGet('test-contact-link');
$this->assertContactLinks($accounts, array('root', 'admin'));
}
示例8: _insertPurchasedProduct
function _insertPurchasedProduct($data)
{
$product_id = $data['id'];
$quantity = $data['quantity'];
$price = $data['price'];
$customer_id = $data['customer_id'];
$note = $data['body'];
$status_id = $data['status_id'];
$total_price = $price * $quantity;
$user_storage = \Drupal::entityManager()->getStorage('user');
$customer = \Drupal\user\Entity\User::load($customer_id);
// update user
if ($status_id != 3) {
if (!isset($customer->field_total_money->value)) {
$customer->field_total_money->value = $total_price;
} else {
$customer->field_total_money->value += $total_price;
}
$customer->field_debt->value = $customer->field_total_money->value - $customer->field_payment_money->value;
$customer->field_last_purchased_date->value = format_date(REQUEST_TIME, 'custom', 'Y-m-d\\TH:i:s');
$user_storage->save($customer);
}
// insert new row
$fields = array('product_id' => $product_id, 'user_id' => $customer_id, 'quantity' => $quantity, 'price' => $price, 'total_price' => $total_price, 'status' => $status_id, 'note' => $note, 'date' => REQUEST_TIME);
db_insert('product_user_relationship')->fields($fields)->execute();
}
示例9: testUserHooks
public function testUserHooks()
{
FieldStorageConfig::create(array('field_name' => 'field_text', 'type' => 'string', 'entity_type' => 'user'))->save();
FieldConfig::create(array('field_name' => 'field_text', 'type' => 'string', 'entity_type' => 'user', 'bundle' => 'user'))->save();
$this->assertIdentical('', \Drupal::config('name.settings')->get('user_preferred'));
FieldStorageConfig::create(array('field_name' => 'field_name_test', 'type' => 'name', 'entity_type' => 'user'))->save();
FieldStorageConfig::create(array('field_name' => 'field_name_test2', 'type' => 'name', 'entity_type' => 'user'))->save();
$field = FieldConfig::create(array('field_name' => 'field_name_test', 'type' => 'name', 'entity_type' => 'user', 'bundle' => 'user'));
$field->save();
$field2 = FieldConfig::create(array('field_name' => 'field_name_test2', 'type' => 'name', 'entity_type' => 'user', 'bundle' => 'user'));
$field2->save();
$this->assertEqual($field->getName(), \Drupal::config('name.settings')->get('user_preferred'));
\Drupal::configFactory()->getEditable('name.settings')->set('user_preferred', $field2->getName())->save();
$field2->delete();
$this->assertEqual('', \Drupal::config('name.settings')->get('user_preferred'));
\Drupal::configFactory()->getEditable('name.settings')->set('user_preferred', $field->getName())->save();
$account = User::create(array('name' => 'test'));
$account->field_name_test[0] = array('given' => 'Max', 'family' => 'Mustermann');
$account->save();
$account = User::load($account->id());
$this->assertEqual('Max Mustermann', $account->realname);
$this->assertEqual('Max Mustermann', user_format_name($account));
$this->assertEqual('test', $account->getUsername());
$this->assertEqual('Max Mustermann', $account->getDisplayName());
}
示例10: create
/**
* {@inheritdoc}
*/
public function create(array $values = array())
{
$store_config = \Drupal::config('uc_store.settings');
// Set the primary email address.
if (empty($values['primary_email']) && !empty($values['uid'])) {
if ($account = User::load($values['uid'])) {
$values['primary_email'] = $account->mail;
}
}
// Set the default order status.
if (empty($values['order_status'])) {
$values['order_status'] = uc_order_state_default('in_checkout');
}
// Set the default currency.
if (empty($values['currency'])) {
$values['currency'] = $store_config->get('currency.code');
}
// Set the default country codes.
if (empty($values['billing_country'])) {
$values['billing_country'] = $store_config->get('address.country');
}
if (empty($values['delivery_country'])) {
$values['delivery_country'] = $store_config->get('address.country');
}
// Set the created time to now.
if (empty($values['created'])) {
$values['created'] = REQUEST_TIME;
}
return parent::create($values);
}
示例11: execute
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
$uid = $input->getArgument('user');
$user = User::load($uid);
if (!$user) {
$io->error(sprintf($this->trans('commands.user.password.reset.errors.invalid-user'), $uid));
return;
}
$password = $input->getArgument('password');
if (!$password) {
$io->error(sprintf($this->trans('commands.user.password.reset.errors.empty-password'), $uid));
return;
}
try {
$user->setPassword($password);
$user->save();
// Clear all failed login attempts after setup new password to user account.
$this->getChain()->addCommand('user:login:clear:attempts', ['uid' => $uid]);
} catch (\Exception $e) {
$io->error($e->getMessage());
return;
}
$io->success(sprintf($this->trans('commands.user.password.reset.messages.reset-successful'), $uid));
}
示例12: setUp
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->installSchema('system', 'sequences');
$this->installEntitySchema('user');
$this->manager = $this->container->get('plugin.manager.condition');
// Set up the authenticated and anonymous roles.
Role::create(array('id' => RoleInterface::ANONYMOUS_ID, 'label' => 'Anonymous user'))->save();
Role::create(array('id' => RoleInterface::AUTHENTICATED_ID, 'label' => 'Authenticated user'))->save();
// Create new role.
$rid = strtolower($this->randomMachineName(8));
$label = $this->randomString(8);
$role = Role::create(array('id' => $rid, 'label' => $label));
$role->save();
$this->role = $role;
// Setup an anonymous user for our tests.
$this->anonymous = User::create(array('name' => '', 'uid' => 0));
$this->anonymous->save();
// Loading the anonymous user adds the correct role.
$this->anonymous = User::load($this->anonymous->id());
// Setup an authenticated user for our tests.
$this->authenticated = User::create(array('name' => $this->randomMachineName()));
$this->authenticated->save();
// Add the custom role.
$this->authenticated->addRole($this->role->id());
}
示例13: checkAccess
/**
* {@inheritdoc}
*
* When the $operation is 'add' then the $entity is of type 'profile_type',
* otherwise $entity is of type 'profile'.
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account)
{
$account = $this->prepareUser($account);
$user_page = \Drupal::request()->attributes->get('user');
// Some times, operation edit is called update.
// Use edit in any case.
if ($operation == 'update') {
$operation = 'edit';
}
// Check that if profile type has require roles, the user the profile is
// being added to has any of the required roles.
if ($entity->getEntityTypeId() == 'profile') {
$profile_roles = ProfileType::load($entity->bundle())->getRoles();
$user_roles = $entity->getOwner()->getRoles(TRUE);
if (!empty(array_filter($profile_roles)) && !array_intersect($user_roles, $profile_roles)) {
return AccessResult::forbidden();
}
} elseif ($entity->getEntityTypeId() == 'profile_type') {
$profile_roles = $entity->getRoles();
$user_roles = User::load($user_page->id())->getRoles(TRUE);
if (!empty(array_filter($profile_roles)) && !array_intersect($user_roles, $profile_roles)) {
return AccessResult::forbidden();
}
}
if ($account->hasPermission('bypass profile access')) {
return AccessResult::allowed()->cachePerPermissions();
} elseif ($operation == 'add' && ($user_page->id() == $account->id() && $account->hasPermission($operation . ' own ' . $entity->id() . ' profile') || $account->hasPermission($operation . ' any ' . $entity->id() . ' profile')) || $operation != 'add' && ($entity->getOwnerId() == $account->id() && $account->hasPermission($operation . ' own ' . $entity->getType() . ' profile') || $account->hasPermission($operation . ' any ' . $entity->getType() . ' profile'))) {
return AccessResult::allowed()->cachePerPermissions();
} else {
return AccessResult::forbidden()->cachePerPermissions();
}
}
示例14: testUserProfileValues
/**
* Tests Drupal 6 profile values to Drupal 8 migration.
*/
public function testUserProfileValues()
{
$user = User::load(2);
$this->assertFalse(is_null($user));
$this->assertIdentical('red', $user->profile_color->value);
$expected = <<<EOT
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam nulla sapien, congue nec risus ut, adipiscing aliquet felis. Maecenas quis justo vel nulla varius euismod. Quisque metus metus, cursus sit amet sem non, bibendum vehicula elit. Cras dui nisl, eleifend at iaculis vitae, lacinia ut felis. Nullam aliquam ligula volutpat nulla consectetur accumsan. Maecenas tincidunt molestie diam, a accumsan enim fringilla sit amet. Morbi a tincidunt tellus. Donec imperdiet scelerisque porta. Sed quis sem bibendum eros congue sodales. Vivamus vel fermentum est, at rutrum orci. Nunc consectetur purus ut dolor pulvinar, ut volutpat felis congue. Cras tincidunt odio sed neque sollicitudin, vehicula tempor metus scelerisque.
EOT;
$this->assertIdentical($expected, $user->profile_biography->value);
$this->assertIdentical('1', $user->profile_sell_address->value);
$this->assertIdentical('Back\\slash', $user->profile_sold_to->value);
$this->assertIdentical('AC/DC', $user->profile_bands[0]->value);
$this->assertIdentical('Eagles', $user->profile_bands[1]->value);
$this->assertIdentical('Elton John', $user->profile_bands[2]->value);
$this->assertIdentical('Lemonheads', $user->profile_bands[3]->value);
$this->assertIdentical('Rolling Stones', $user->profile_bands[4]->value);
$this->assertIdentical('Queen', $user->profile_bands[5]->value);
$this->assertIdentical('The White Stripes', $user->profile_bands[6]->value);
$this->assertIdentical('1974-06-02', $user->profile_birthdate->value);
$this->assertIdentical('http://example.com/blog', $user->profile_blog->uri);
$this->assertNull($user->profile_blog->title);
$this->assertIdentical([], $user->profile_blog->options);
$this->assertIdentical('http://example.com/blog', $user->profile_blog->uri);
$this->assertNull($user->profile_love_migrations->value);
$user = User::load(8);
$this->assertIdentical('Forward/slash', $user->profile_sold_to->value);
$user = User::load(15);
$this->assertIdentical('Dot.in.the.middle', $user->profile_sold_to->value);
}
示例15: execute
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
$uid = $input->getArgument('uid');
$account = User::load($uid);
if (!$account) {
// Error loading User entity.
$io->error(sprintf($this->trans('commands.user.login.clear.attempts.errors.invalid-user'), $uid));
return 1;
}
// Define event name and identifier.
$event = 'user.failed_login_user';
// Identifier is created by uid and IP address,
// Then we defined a generic identifier.
$identifier = "{$account->id()}-";
// Retrieve current database connection.
$database = $this->getDrupalService('database');
$schema = $database->schema();
$flood = $schema->findTables('flood');
if (!$flood) {
$io->error($this->trans('commands.user.login.clear.attempts.errors.no-flood'));
return 1;
}
// Clear login attempts.
$database->delete('flood')->condition('event', $event)->condition('identifier', $database->escapeLike($identifier) . '%', 'LIKE')->execute();
// Command executed successful.
$io->success(sprintf($this->trans('commands.user.login.clear.attempts.messages.successful'), $uid));
}