更改字段值并使用自定义按钮提交节点

时间:2018-12-21 21:25:05

标签: drupal drupal-7 drupal-modules

我正在尝试编写一个向节点类型添加按钮的模块,该模块在被按下时将更改该节点中字段的值并提交更改。一切似乎都正常,因为按钮正确显示,并且节点在按下时提交,但是该字段的值保持不变。我觉得我缺少明显的东西。

<?php

function iu_buttons_node_view($node, $view_mode, $langcode) {
    if ($node->type == 'billing_entry') {
        if ($node->field_status['und'][0]['value'] == 'open') {
            $form = drupal_get_form('submit_button_form');
            $node->content['submit_button'] = $form;
        }
    }
}

function submit_button_form($form, &$form_submit) {
    $form['submit'] = array(
        '#type' => 'button',
        '#value' => ('Submit'),
        '#submit' => array('submit_button_form_submit'),
    );
    return $form;
}

function submit_button_form_submit($form, &$form_state) {
    $node->field_status['und'][0]['value']['#value'] = 'submitted';
}

可能值得注意的是,我要更改的字段是一个选择列表。我应该使用与hook_form_submit不同的功能吗?

1 个答案:

答案 0 :(得分:0)

我假设您是在名为 iu_buttons 的自定义模块中编写此代码的,并且您希望在节点页面中而不是在节点编辑表单中显示此按钮。

在这种情况下,问题在于您从未在提交功能中保存该节点。这是提交功能的一个版本,它将保存该节点。

function submit_button_form_submit($form, &$form_state) {
    $node = menu_get_object(); //get the current node
    $node->field_status['und'][0]['value']['#value'] = 'submitted';
    node_save($node); // save the changed node
}

我认为您可能只想保存字段,而不需要保存整个节点。在这种情况下,您可以使用以下内容:

function submit_button_form_submit($form, &$form_state){
   $node = new stdClass(); // Create empty object
   $node->nid = intval(args(1)); // Include the nid so that Drupal saves the new value to the correct node
   $node->field_status['und'][0]['value']['#value'] = 'submitted';
   field_attach_update('node', $node); // Save the field
}
相关问题