hook_template_preprocess_default_variables_alter
修改模板的默认变量
function hook_template_preprocess_default_variables_alter(&$variables) {
$variables['is_admin'] = \Drupal::currentUser()->hasPermission('access administration pages');
}
hook_form_alter
修改表单
一个受欢迎的用法是将表单元素添加到节点形式
dpm($form);
function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if (isset($form['type']) && $form['type']['#value'] . '_node_settings' == $form_id) {
$upload_enabled_types = \Drupal::config('mymodule.settings')->get('upload_enabled_types');
$form['workflow']['upload_' . $form['type']['#value']] = [
'#type' => 'radios',
'#title' => t('Attachments'),
'#default_value' => in_array($form['type']['#value'], $upload_enabled_types) ? 1 : 0,
'#options' => [t('Disabled'), t('Enabled')],
];
// Add a custom submit handler to save the array of types back to the config file.
$form['actions']['submit']['#submit'][] = 'mymodule_upload_enabled_types_submit';
}
}
// 判断form表单提交按钮的类型,给对应元素添加类
function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if (isset($form['actions']['submit']['#button_type'])){
if($form['actions']['submit']['#button_type'] === 'primary'){
$form['actions']['submit']['attributes']['class'][] = 'btn btn-primary';
}
}
if (isset($form['actions']['submit']['#button_type'])){
if($form['actions']['submit']['#button_type'] === 'danger'){
$form['actions']['submit']['attributes']['class'][] = 'btn btn-danger';
}
}
}
template_preprocess_table
修改表格
function hook_preprocess_table(&$variables){
$variables['attributes']['class'][] = 'table';
$variables['attributes']['class'][] = 'table-boreder';
$variables['#attached']['library'][] = 'themename/table'
}
template_preprocess_views_view_table
视图表格
function hook_preprocess_views_view_table(&$variables){
$variables['attributes']['class'][] = 'table';
$variables['attributes']['class'][] = 'table-boreder';
$variables['#attached']['library'][] = 'themename/views-table'
}
preprocess_form_element
表单元素预处理
function hook_preprocess_form_element(&$variables){
// 元素的type赋值给label #attributes 下面的type,就可以在twig模板里面判断使用。
$variables['label']['#attributes']['type'] = $variables['type'];
}