能否通过链接加载Drupal节点编辑模式并预设发布选项为已发布?
Got it, let's tackle this problem without prematurely saving the node. The key here is to modify the edit form's default value for the published checkbox, and only apply the status change when the user actually saves the node—no pre-saves required.
Step 1: Use hook_form_alter() to set the default checkbox state
Create or edit your custom module, then add this hook to tweak the node edit form:
/** * Implements hook_form_alter(). */ function your_custom_module_form_alter(&$form, &$form_state, $form_id) { // Target all node edit forms (adjust this if you need specific content types) if (strpos($form_id, 'node_form') !== FALSE) { $node = $form_state['node']; // Check if the node is currently unpublished, and we're triggering this via our custom redirect // We'll use a query parameter to flag when we want this behavior $auto_publish_trigger = isset($_GET['auto_publish']) && $_GET['auto_publish'] === '1'; if ($node->status == NODE_NOT_PUBLISHED && $auto_publish_trigger) { // Set the published checkbox to be checked by default $form['status']['#default_value'] = 1; // Add a hidden field to track this trigger for the save step $form['auto_publish_trigger'] = [ '#type' => 'hidden', '#value' => 1, ]; } } }
Step 2: Use hook_node_presave() to apply the status change on save
Next, add this hook to update the node's status only when the form is submitted:
/** * Implements hook_node_presave(). */ function your_custom_module_node_presave($node) { // Verify we have our trigger, and the node was originally unpublished if (isset($_POST['auto_publish_trigger']) && $_POST['auto_publish_trigger'] == 1 && $node->original->status == NODE_NOT_PUBLISHED) { // Set the node to published right before saving $node->status = NODE_PUBLISHED; } }
Step 3: Update your redirect to include the trigger parameter
Instead of a plain drupal_goto, add the auto_publish query parameter to flag when we want the checkbox pre-checked:
// Redirect to the node edit form with our trigger flag drupal_goto("node/{$node->nid}/edit", ['query' => ['auto_publish' => '1']]);
How this works
- When you redirect with the
auto_publish=1parameter,hook_form_alterdetects it and checks the "Published" checkbox by default—but the node itself stays unpublished until save. - The hidden field tracks that we want to apply the status change on submission.
hook_node_presavekicks in right before the node is saved, checks the trigger, and updates the status only if the node was originally unpublished.
Optional: Adjust for specific use cases
If you don't want to use a query parameter (e.g., this should apply to all unpublished nodes of a specific type), modify the hook_form_alter condition:
// Example: Target only unpublished article nodes if ($form_id == 'node_article_form' && $node->status == NODE_NOT_PUBLISHED) { // Set default value and hidden field here }
内容的提问来源于stack exchange,提问作者Markus

