当前位置: 首页>>代码示例>>PHP>>正文


PHP Drupal::currentUser方法代码示例

本文整理汇总了PHP中Drupal::currentUser方法的典型用法代码示例。如果您正苦于以下问题:PHP Drupal::currentUser方法的具体用法?PHP Drupal::currentUser怎么用?PHP Drupal::currentUser使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Drupal的用法示例。


在下文中一共展示了Drupal::currentUser方法的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);
 }
开发者ID:augustpascual-mse,项目名称:job-searching-network,代码行数:25,代码来源:JobHistoryController.php

示例2: checkConfigurationAccess

 /**
  * Checks configuration permission.
  *
  * @param AccountInterface $account
  *   (optional) The user for which to check access, or NULL to check access
  *   for the current user. Defaults to NULL.
  * @param bool $return_as_object
  *   (optional) Defaults to FALSE.
  *
  * @return bool|\Drupal\Core\Access\AccessResultInterface
  *   The access result. Returns a boolean if $return_as_object is FALSE (this
  *   is the default) and otherwise an AccessResultInterface object.
  *   When a boolean is returned, the result of AccessInterface::isAllowed() is
  *   returned, i.e. TRUE means access is explicitly allowed, FALSE means
  *   access is either explicitly forbidden or "no opinion".
  */
 public function checkConfigurationAccess(AccountInterface $account = NULL, $return_as_object = FALSE)
 {
     if (!$account) {
         $account = \Drupal::currentUser();
     }
     // We treat these as our "super-user" accesses.  We let the reaction
     // rule and component permissions control the main admin UI.
     $admin_perms = ['administer rules', 'bypass rules access'];
     $access = FALSE;
     foreach ($admin_perms as $perm) {
         if ($account->hasPermission($perm)) {
             $access = TRUE;
             break;
         }
     }
     if (!$access) {
         // See if the plugin has a configuration_access annotation.
         $definition = $this->getPluginDefinition();
         if (!empty($definition['configure_permissions']) && is_array($definition['configure_permissions'])) {
             foreach ($definition['configure_permissions'] as $perm) {
                 if ($account->hasPermission($perm)) {
                     $access = TRUE;
                     break;
                 }
             }
         }
     }
     if ($return_as_object) {
         return $access ? AccessResult::allowed() : AccessResult::neutral();
     }
     return $access;
 }
开发者ID:Progressable,项目名称:openway8,代码行数:48,代码来源:ConfigurationAccessControlTrait.php

示例3: checkForUserPasswordExpiration

 /**
  * Event callback to look for users expired password
  */
 public function checkForUserPasswordExpiration(GetResponseEvent $event)
 {
     $account = \Drupal::currentUser();
     // There needs to be an explicit check for non-anonymous or else
     // this will be tripped and a forced redirect will occur.
     if ($account->id() > 0) {
         /** @var $user \Drupal\user\UserInterface */
         $user = entity_load('user', $account->id());
         $route_name = \Drupal::request()->attributes->get(RouteObjectInterface::ROUTE_NAME);
         ///system/ajax
         $ignored_routes = array('entity.user.edit_form', 'system.ajax', 'user.logout');
         $user_expired = FALSE;
         if ($user->get('field_password_expiration')->get(0)) {
             $user_expired = $user->get('field_password_expiration')->get(0)->getValue();
             $user_expired = $user_expired['value'];
         }
         //TODO - Consider excluding admins here
         if ($user_expired and !in_array($route_name, $ignored_routes)) {
             $url = new Url('entity.user.edit_form', array('user' => $user->id()));
             $url = $url->toString();
             $event->setResponse(new RedirectResponse($url));
             drupal_set_message('Your password has expired, please update it', 'error');
         }
     }
 }
开发者ID:nerdstein,项目名称:password_policy,代码行数:28,代码来源:PasswordPolicyEventSubscriber.php

示例4: __construct

 /**
  * Constructs the file manager.
  *
  * @param array $conf
  *   File manager configuration
  * @param \Drupal\Core\Session\AccountProxyInterface $user
  *   The active user
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The active request that contains parameters for file manager operations
  */
 public function __construct(array $conf, AccountProxyInterface $user = NULL, Request $request = NULL)
 {
     $this->conf = $conf;
     $this->user = $user ?: \Drupal::currentUser();
     $this->request = $request;
     $this->init();
 }
开发者ID:aakb,项目名称:cfia,代码行数:17,代码来源:ImceFM.php

示例5: submitForm

 /**
  * {@inheritdoc}
  */
 public function submitForm(OrderInterface $order, array &$form, FormStateInterface $form_state)
 {
     if (!$form_state->isValueEmpty('admin_comment')) {
         $uid = \Drupal::currentUser()->id();
         uc_order_comment_save($form_state->getValue('order_id'), $uid, $form_state->getValue('admin_comment'));
     }
 }
开发者ID:justincletus,项目名称:webdrupalpro,代码行数:10,代码来源:AdminComments.php

示例6: 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.');
 }
开发者ID:augustpascual-mse,项目名称:job-searching-network,代码行数:30,代码来源:ApplyForm.php

示例7: view

 /**
  * {@inheritdoc}
  */
 public function view(OrderInterface $order, $view_mode)
 {
     $build = array('#type' => 'table', '#attributes' => array('class' => array('order-pane-table')), '#header' => array('qty' => array('data' => $this->t('Quantity'), 'class' => array('qty')), 'product' => array('data' => $this->t('Product'), 'class' => array('product')), 'model' => array('data' => $this->t('SKU'), 'class' => array('sku', RESPONSIVE_PRIORITY_LOW)), 'cost' => array('data' => $this->t('Cost'), 'class' => array('cost', RESPONSIVE_PRIORITY_LOW)), 'price' => array('data' => $this->t('Price'), 'class' => array('price')), 'total' => array('data' => $this->t('Total'), 'class' => array('price'))), '#empty' => $this->t('This order contains no products.'));
     $account = \Drupal::currentUser();
     if (!$account->hasPermission('administer products')) {
         unset($build['#header']['cost']);
     }
     // @todo Replace with Views.
     foreach ($order->products as $id => $product) {
         $build[$id]['qty'] = array('#theme' => 'uc_qty', '#qty' => $product->qty->value, '#cell_attributes' => array('class' => array('qty')));
         if ($product->nid->entity && $product->nid->entity->access('view')) {
             $title = Link::createFromRoute($product->title->value, 'entity.node.canonical', ['node' => $product->nid->target_id])->toString();
         } else {
             $title = $product->title->value;
         }
         $build[$id]['product'] = array('#markup' => $title . uc_product_get_description($product), '#cell_attributes' => array('class' => array('product')));
         $build[$id]['model'] = array('#markup' => $product->model->value, '#cell_attributes' => array('class' => array('sku')));
         if ($account->hasPermission('administer products')) {
             $build[$id]['cost'] = array('#theme' => 'uc_price', '#price' => $product->cost->value, '#cell_attributes' => array('class' => array('cost')));
         }
         $build[$id]['price'] = array('#theme' => 'uc_price', '#price' => $product->price->value, '#suffixes' => array(), '#cell_attributes' => array('class' => array('price')));
         $build[$id]['total'] = array('#theme' => 'uc_price', '#price' => $product->price->value * $product->qty->value, '#suffixes' => array(), '#cell_attributes' => array('class' => array('total')));
         //      $build[$id][$field]['#wrapper_attributes']['class'] = $build['#header'][$field]['class'];
     }
     return $build;
 }
开发者ID:justincletus,项目名称:webdrupalpro,代码行数:29,代码来源:Products.php

示例8: attach_file

 public static function attach_file($uri)
 {
     $user = \Drupal::currentUser();
     $file = entity_create('file', array('uri' => $uri, 'uid' => $user->id(), 'status' => FILE_STATUS_PERMANENT));
     $file->save();
     return $file;
 }
开发者ID:318io,项目名称:318-io,代码行数:7,代码来源:WG.php

示例9: setUp

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->drupalPlaceBlock('local_tasks_block');
    $this->drupalPlaceBlock('local_actions_block');
    $this->drupalPlaceBlock('page_title_block');

    $this->adminUser = $this->drupalCreateUser([
      'administer products',
      'administer product types',
      'administer commerce_product fields',
      'access administration pages',
      'administer commerce_product_variation fields'
    ]);
    $this->drupalLogin($this->adminUser);

    $storeType = $this->createEntity('commerce_store_type', [
      'id' => strtolower($this->randomMachineName(8)),
      'label' => $this->randomMachineName(8),
    ]);

    $this->stores = [];
    for ($i = 0; $i < 3; $i++) {
      $this->stores[] = $this->createEntity('commerce_store', [
        'type' => $storeType->id(),
        'name' => $this->randomMachineName(8),
        'mail' => \Drupal::currentUser()->getEmail(),
        'default_currency' => 'EUR',
      ]);
    }
  }
开发者ID:housineali,项目名称:drpl8_dv,代码行数:34,代码来源:ProductTestBase.php

示例10: chargeCard

 /**
  * {@inheritdoc}
  */
 protected function chargeCard($order, $amount, $txn_type, $reference = NULL)
 {
     $user = \Drupal::currentUser();
     // cc_exp_month and cc_exp_year are also validated by
     // _uc_credit_valid_card_expiration() on the checkout form.
     $month = $order->payment_details['cc_exp_month'];
     $year = $order->payment_details['cc_exp_year'];
     if ($year < 100) {
         $year = $year + 2000;
     }
     // Card is expired at 0:00 on the first day of the next month.
     $expiration_date = mktime(0, 0, 0, $month + 1, 1, $year);
     // Conditions for failure are described in file documentation block above.
     // All other transactions will succeed.
     if ($order->payment_details['cc_number'] == '0000000000000000' || isset($order->payment_details['cc_cvv']) && $order->payment_details['cc_cvv'] == '000' || $expiration_date - REQUEST_TIME <= 0 || $amount == 12.34 || $order->billing_first_name == 'Fictitious' || $order->billing_phone == '8675309') {
         $success = FALSE;
     } else {
         $success = TRUE;
     }
     // The information for the payment is in the $order->payment_details array.
     if ($this->configuration['debug']) {
         \Drupal::logger('uc_credit')->notice('Test gateway payment details @details.', ['@details' => print_r($order->payment_details, TRUE)]);
     }
     if ($success) {
         $message = $this->t('Credit card charged: @amount', ['@amount' => uc_currency_format($amount)]);
         uc_order_comment_save($order->id(), $user->id(), $message, 'admin');
     } else {
         $message = $this->t('Credit card charge failed.');
         uc_order_comment_save($order->id(), $user->id(), $message, 'admin');
     }
     $result = array('success' => $success, 'comment' => $this->t('Card charged, resolution code: 0022548315'), 'message' => $success ? $this->t('Credit card payment processed successfully.') : $this->t('Credit card charge failed.'), 'uid' => $user->id());
     return $result;
 }
开发者ID:justincletus,项目名称:webdrupalpro,代码行数:36,代码来源:TestGateway.php

示例11: allowed

 /**
  * {@inheritdoc}
  */
 public function allowed(WorkflowTransition $transition, WorkflowInterface $workflow, EntityInterface $entity)
 {
     $to_state = $transition->getToState()->getId();
     // Disable virtual state.
     if ($to_state == self::NON_STATE) {
         return FALSE;
     }
     $from_state = $this->getState($entity);
     // Allowed transitions are already filtered so we only need to check
     // for the transitions defined in the settings if they include a role the
     // user has.
     // @see: solution.settings.yml
     $allowed_conditions = \Drupal::config('solution.settings')->get('transitions');
     if (\Drupal::currentUser()->hasPermission('bypass node access')) {
         return TRUE;
     }
     // Check if the user has one of the allowed system roles.
     $authorized_roles = isset($allowed_conditions[$to_state][$from_state]) ? $allowed_conditions[$to_state][$from_state] : [];
     $user = $this->workflowUserProvider->getUser();
     if (array_intersect($authorized_roles, $user->getRoles())) {
         return TRUE;
     }
     // Check if the user has one of the allowed group roles.
     $membership = Og::getMembership($entity, $user);
     return $membership && array_intersect($authorized_roles, $membership->getRolesIds());
 }
开发者ID:ec-europa,项目名称:joinup-dev,代码行数:29,代码来源:SolutionFulfillmentGuard.php

示例12: form

 /**
  * Overrides Drupal\Core\Entity\EntityForm::form().
  */
 public function form(array $form, array &$form_state)
 {
     $user = $this->currentUser();
     /** @var \Drupal\user\UserInterface $account */
     $account = $this->entity;
     $admin = $user->hasPermission('administer users');
     // Pass access information to the submit handler. Running an access check
     // inside the submit function interferes with form processing and breaks
     // hook_form_alter().
     $form['administer_users'] = array('#type' => 'value', '#value' => $admin);
     // If we aren't admin but already logged on, go to the user page instead.
     if (!$admin && $user->isAuthenticated()) {
         return new RedirectResponse(url('user/' . \Drupal::currentUser()->id(), array('absolute' => TRUE)));
     }
     $form['#attached']['library'][] = 'core/jquery.cookie';
     $form['#attributes']['class'][] = 'user-info-from-cookie';
     // Because the user status has security implications, users are blocked by
     // default when created programmatically and need to be actively activated
     // if needed. When administrators create users from the user interface,
     // however, we assume that they should be created as activated by default.
     if ($admin) {
         $account->activate();
     }
     // Start with the default user account fields.
     $form = parent::form($form, $form_state, $account);
     if ($admin) {
         // Redirect back to page which initiated the create request; usually
         // admin/people/create.
         $form_state['redirect'] = current_path();
     }
     return $form;
 }
开发者ID:alnutile,项目名称:drunatra,代码行数:35,代码来源:RegisterForm.php

示例13: testRegistration

 /**
  * Create new registration via UI.
  *
  * Enable registrations for an event and submit new registration form.
  */
 function testRegistration()
 {
     // Event
     $base_url = 'node/1';
     $this->drupalGet($base_url . '');
     $this->assertResponse(200);
     $this->drupalGet($base_url . '/event');
     $this->assertResponse(200);
     $this->assertNoLinkByHref($base_url . '/register');
     $this->drupalGet($base_url . '/register');
     $this->assertResponse(403);
     // Settings
     $edit = ['rng_status[value]' => TRUE, 'rng_registration_type[' . $this->registration_type->id() . ']' => TRUE, 'rng_capacity[0][unlimited_number][unlimited_number]' => 'limited', 'rng_capacity[0][unlimited_number][number]' => '1'];
     $this->drupalPostForm($base_url . '/event', $edit, t('Save'));
     $this->assertRaw(t('Event settings updated.'));
     // Register tab appears.
     $this->assertLinkByHref($base_url . '/register');
     // Registration form.
     $this->drupalGet($base_url . '/register');
     $this->assertResponse(200);
     $this->assertRaw(t('My account: %username', ['%username' => \Drupal::currentUser()->getAccountName()]));
     $edit = ['identity' => 'user:' . \Drupal::currentUser()->id()];
     $this->drupalPostForm($base_url . '/register', $edit, t('Save'));
     $this->assertRaw(t('Registration has been created.'));
 }
开发者ID:justincletus,项目名称:webdrupalpro,代码行数:30,代码来源:RegistrationTest.php

示例14: actions

 /**
  * {@inheritdoc}
  */
 protected function actions(array $form, FormStateInterface $form_state)
 {
     $actions = parent::actions($form, $form_state);
     $actions['submit']['#value'] = $this->t('Save task');
     $actions['submit']['#access'] = \Drupal::currentUser()->hasPermission('administer tmgmt') || \Drupal::currentUser()->hasPermission('administer translation tasks');
     return $actions;
 }
开发者ID:andrewl,项目名称:andrewlnet,代码行数:10,代码来源:LocalTaskForm.php

示例15: testHandlers

 /**
  * Tests the handlers.
  */
 public function testHandlers()
 {
     $nodes = array();
     $nodes[] = $this->drupalCreateNode();
     $nodes[] = $this->drupalCreateNode();
     $account = $this->drupalCreateUser();
     $this->drupalLogin($account);
     \Drupal::currentUser()->setAccount($account);
     db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[0]->id(), 'timestamp' => REQUEST_TIME - 100))->execute();
     db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[1]->id(), 'timestamp' => REQUEST_TIME + 100))->execute();
     $column_map = array('nid' => 'nid');
     // Test the history field.
     $view = Views::getView('test_history');
     $view->setDisplay('page_1');
     $this->executeView($view);
     $this->assertEqual(count($view->result), 2);
     $output = $view->preview();
     $this->setRawContent(\Drupal::service('renderer')->renderRoot($output));
     $result = $this->xpath('//span[@class=:class]', array(':class' => 'marker'));
     $this->assertEqual(count($result), 1, 'Just one node is marked as new');
     // Test the history filter.
     $view = Views::getView('test_history');
     $view->setDisplay('page_2');
     $this->executeView($view);
     $this->assertEqual(count($view->result), 1);
     $this->assertIdenticalResultset($view, array(array('nid' => $nodes[0]->id())), $column_map);
 }
开发者ID:HakS,项目名称:drupal8_training,代码行数:30,代码来源:HistoryTimestampTest.php


注:本文中的Drupal::currentUser方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。