drupal8插件开发用到的一些常用函数

//引用表单

\Drupal::formBuilder()->getForm("\Drupal\xxx\Form\xxxx");

//判断是否登录的函数

\Drupal::currentUser()->isAuthenticated();

//获取用户信息

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$user->get('mail')->value;

//增加提示语的函数

\Drupal::messenger()->addWarning();

//跳转函数

$this->redirect('','');

//输出json

return new JsonResponse();

//模板传递的方法,先在.module的文件定义

function xxxx_theme($existing, $type, $theme, $path)
{
    return [
            'xxxxxx' => [
             'variables' => [],
             ],
             'xxxxxx' => [
             'variables' => [],
             ],
          ]
}

控制器Controller

return array(
   '#theme' => 'xxxxx',
)

表单一般由三部分组成

public function buildForm(array $form, FormStateInterface $form_state)
{
   //接收参数方法
   $pammer = $form_state->getValue("pammer");
   
   $form = array();
    $form['summary'] = array(
      '#type' => 'textfield',
      '#title' => 'Subject <span class="description">(Maximum 128 characters)</span>',
      '#required' => true,
      '#prefix' => '<div class="field-summary">',
      '#suffix' => '</div>',
      '#maxlength' => 128,
    );
  return $form; 
}

public function validateForm(array & $form, FormStateInterface $form_state)
{
  //提示语的写法
  $form_state->setErrorByName('summary', $this->t('xxx'));
}

public function submitForm(array & $form, FormStateInterface $form_state)
{
  //跳转的写法
  $url = Url::fromRoute('xxx', ['id' =>'']);
  return $form_state->setRedirectUrl($url);
}
标签:

发表评论