题
当我按某些内容上的删除按钮时,我将被带到确认页面。删除选项是一个按钮,而取消选项是链接。看起来很奇怪。我发现Drupal中有一个Form_Confirm()函数,但我不明白如何使用它。有人知道如何将取消链接放入按钮吗?
解决方案
或使用no JavaScript(并用preg_match()替换Eregi()...
if ( $form['#theme'] == 'confirm_form' ) {
$no = $form['actions']['cancel']['#value'];
if (!is_null($no)) {
// Get the text to put on the cancel button
$value = preg_replace('/(<\/?)(\w+)([^>]*>)/e', '', $no);
preg_match('/href\s*=\s*\"([^\"]+)\"/', $no, $href);
$form['actions']['cancel']['#value'] = '';
$form['href']=array(
'#type'=>'value',
'#value'=>$href[1],
);
// Add our own button
$form['actions']['docancel'] = array(
'#type' => 'submit',
'#name' => 'cancel',
'#submit' => array('mymodule_confirm_form_cancel'),
'#value' => $value,
);
}
}
和
function mymodule_confirm_form_cancel(&$form,&$form_state) {
$href=$form['href']['#value'];
if ( !is_null($href) ) {
$form['#redirect']=$href;
}
}
其他提示
取消链接看起来像链接的原因是因为它是链接 <a>
, ,而确认按钮是表单提交元素 <input type="submut>
.
如果您想制作取消链接,看起来像一个提交按钮,可以使用纯CSS进行操作。
使用hook_form_alter(),请尝试以下操作:
if($form['#theme'] == 'confirm_form') {
$no = $form['actions']['cancel']['#value'];
if (!is_null($no)) {
// Get the text to put on the cancel button
$value = preg_replace('/(<\/?)(\w+)([^>]*>)/e', '', $no);
eregi('m|href\s*=\s*\"([^\"]+)\"|ig', $no, $href);
$form['actions']['cancel']['#value'] = '';
// Add our own button
$form['actions']['docancel'] = array(
'#type' => 'button',
'#button_type' => 'reset',
'#name' => 'cancel',
'#submit' => 'false',
'#value' => $value,
'#attributes' => array(
'onclick' => '$(this).parents("form").attr("allowSubmission", "false");window.location = "'.$href[1].'";',
),
);
// Prevent the form submission via our button
$form['#attributes']['onsubmit'] = 'if ($(this).attr("allowSubmission") == "false") return false;';
}
}
对于Drupal 7,我使用:
/**
* Implements hook_form_alter().
*/
function yourmodule_form_alter(&$form, $form_state, $form_id) {
// Change 'cancel' link to 'cancel' button.
if ( $form['#theme'] == 'confirm_form' ) {
if ($form['actions']['cancel']['#type'] == 'link') {
$title = $form['actions']['cancel']['#title'];
$href = $form['actions']['cancel']['#href'];
if (!is_null($title) and !is_null($href)) {
// Disable Cancel link.
$form['actions']['cancel']['#title'] = '';
// Add our own Cancel button.
$form['actions']['docancel'] = array(
'#type' => 'submit',
'#name' => 'cancel',
'#submit' => array('yourmodule_confirm_form_cancel'),
'#value' => $title,
);
}
}
}
}
/**
* Redirect to previous page after confirm form cancel().
*/
function yourmodule_confirm_form_cancel(&$form, &$form_state) {
$href = $form['actions']['cancel']['#href'];
if (!is_null($href)) {
$form_state['redirect'] = $href;
}
}
Drupal 8也报道了问题,但Drupal Core团队无意以核心解决该问题。请参阅Drupal支持请求 更改确认表取消链接到按钮.
最好的问候,巴索。
不隶属于 StackOverflow