如何在PHP表单中返回未保存的变量?

时间:2016-09-21 10:47:02

标签: php forms drupal-7

解决:感谢@riggsfolly指出我正确的方向。我应该先看看Drupal Forms API。添加了“item”类型的表单元素,它就像魅力一样:

$form['description'] = array('#type'=> 'item', '#title'=> t('To maintain consistency across your course, use the link below to select whether you plan to grade assessments based on points or percentages.'),);

更新:我应该提到这是一个Drupal表单。遗憾。

[PHP新手]我正在使用以下代码,我没有写:

function grading_method_form($form, &$form_state){
    $courseId = $_SESSION['courseId'];
    $gradingMethodDetails = getCourseGradingMethod($courseId);
    $form = array();
    $form['cid'] = array('#title'=>NULL,'#type'=>'hidden','#required'=>TRUE,'#value'=>$courseId,);
    $form['grading_method'] = array('#title'=>'','#type'=>'select','#default_value'=>$gradingMethodDetails['grading_method'],'#options'=>array(0=>'Percentage',1=>'Points'),);
    $form['submit'] = array('#type'=>'submit','#value'=>t('Save Grading Method'));
    return $form;
}

我希望在这个非常简单的表单中包含的内容是用户对此处所做的内容的描述。我试过添加这个:

$form .= "To maintain consistency across your course, use the link below to select whether you plan to grade assessments based on points or percentages.";

并且尝试将整个表单移动到另一种方法中我在其他地方看到我使用$form .= 'My description info.';将其他行连接到表单中无效。

我想要做的就是在选择之前在表单中包含一个声明,告知用户这是为了什么。

谢谢!

2 个答案:

答案 0 :(得分:3)

$form是一个数组,您需要做的就是向数组添加另一个出现,如

function grading_method_form($form, &$form_state){
    $courseId = $_SESSION['courseId'];
    $gradingMethodDetails = getCourseGradingMethod($courseId);
    $form = array();
    $form['cid'] = array('#title'=>NULL,'#type'=>'hidden','#required'=>TRUE,'#value'=>$courseId,);
    $form['grading_method'] = array('#title'=>'','#type'=>'select','#default_value'=>$gradingMethodDetails['grading_method'],'#options'=>array(0=>'Percentage',1=>'Points'),);
    $form['submit'] = array('#type'=>'submit','#value'=>t('Save Grading Method'));


    $form['new_message'] = "To maintain consistency across your course, use the link below to select whether you plan to grade assessments based on points or percentages.";

    return $form;
}

当然,您必须查看处理此函数结果的代码,并针对此新发生做适当的事情。

答案 1 :(得分:1)

如果我理解你的问题。您正在尝试向$ form数组添加另一个值。

因为它是一个数组,所以你不能像$ form那样附加一个字符串。=' text';

你可以,如果只是一个变量,例如:

$form = 'hello';
$form .= ' this is a form';
echo $form;

这将显示'你好,这是一个表格'

但是因为你的$ form是一个数组,你必须在liek上添加字符串:

$form['string'] = 'your string'; 

喜欢这样的东西:

array(

    ['string'] => 'your string'

)

对于$ form的其余部分,它看起来像是:

Array
(
[cid] => Array
    (
        [#title] => 
        [#type] => hidden
        [#required] => 1
        [#value] => 1
    )

[grading_method] => Array
    (
        [#title] => 
        [#type] => select
        [#default_value] => 1
        [#options] => Array
            (
                [0] => Percentage
                [1] => Points
            )

    )

[submit] => Array
    (
        [#type] => submit
        [#value] => 1
    )
[string] => 'your text string here'

)