我正在拉两个随机数以创建一个 symfony 形式的数学方程。问题是表单提交时,随机数更新,导致表单提交无效。如何保持加载初始数值,以便表单处理,但成功处理后,加载一个新集合?
动作类
public function executeIndex(sfWebRequest $request)
{
$num1 = rand(0 , 20);
$num2 = rand(0 , 20);
$realAnswer = $num1 + $num2;
$show = $num1 . " + " . $num2 . " = ";
$this->getResponse()->setSlot("displayNum", $show);
$this->form = new UserForm();
echo $num1 . "<br>" . $num2 . "<br>" . $realAnswer;
if ($request->isMethod('post') && ($request->getPostParameter('captcha[answer]') == $realAnswer))
{
$this->processForm($request, $this->form);
}
}
我正在使用部分来呈现表单-> _form.php
<tr height="40">
<td width="100" valign="middle">
<?php echo get_slot("displayNum", "default value if slot doesn't exist"); ?>
</td>
<td width="400" colspan="4" valign="middle">
<input type="text" id="captcha" class="url" name="captcha[answer]" style="width:100px" />
</td>
</tr>
示例:页面最初加载时,会生成两个随机数(例如 10 和 15)。这将呈现 10 + 15 =(输入字段)
用户插入 25 并点击保存。这是正确的,但是因为表单再次执行索引操作,所以有一组新的随机数使“if”条件为假。
更新:
根据 j0k 的建议,我已对操作进行了更改。
public function executeIndex(sfWebRequest $request)
{
$user = $this->getUser();
if (!$request->isMethod('post'))
{
// first display of the form, generate nums
$num1 = rand(0 , 20);
$num2 = rand(0 , 20);
$realAnswer = $num1 + $num2;
// store them in session
$user->setAttribute('realAnswer', $realAnswer);
$user->setAttribute('num1', $num1);
$user->setAttribute('num2', $num2);
}
else
{
// the form is submitted, retrieve nums from the session
$num1 = $user->getAttribute('realAnswer', null);
$num2 = $user->getAttribute('num1', null);
$realAnswer = $user->getAttribute('num2', null);
}
//setup slot
$show = $num1 . " + " . $num2 . " = ";
echo $realAnswer . "-Actual<br>" . $request->getPostParameter('captcha[answer]') . "-User submitted";
$this->form = new UserForm();
if ($request->isMethod('post') && (($request->getPostParameter('captcha[answer]') == $realAnswer)))
{
$this->processForm($request, $this->form);
}
}
这应该工作。查看变量,看起来页面正在拉动会话变量,而不是在第二篇文章中添加新的随机数。奇怪的。
解决
这是一个代码错误。我把变量交叉了。
else
{
// the form is submitted, retrieve nums from the session
$num1 = $user->getAttribute('num1', null);
$num2 = $user->getAttribute('num2', null);
$realAnswer = $user->getAttribute('realAnswer', null);
../