I am pulling two random numbers to create a math equation in a symfony form. The problem is when the form is submitted, the random numbers are updated, making the form submission invalid. How can I keep the initial number values loaded, so the form will process, but after successful process, load a new set?
actions.class
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);
}
}
I am using a partial to render the 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>
Example: When the page initially loads, two random numbers are generated (ex. 10 & 15). This renders 10 + 15 = (input field)
The user inserts 25 and clicks save. This was correct, but because the form executes the index action again, there is a new set of random numbers making the "if" condition false.
UPDATE:
Per j0k's suggestion I have made the changes to the action.
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);
}
}
which should work. Looking at the variables, it looks like the page is pulling the session variable and not adding new random numbers on the second post. weird.
RESOLVED
It was a code error. I had the variables crossed up.
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);
../
tempAnswer
does? – j0k