In my forum when I add a topic, I have a dropdown with all possible categories. When I post and one of the text fields is empty there comes an error, and I want to keep the selected item in the dropdown selected.
I did it before but not with Smarty. Can somebody see what I am doing wrong?
$query_cat = "
SELECT
fcID
,fcName
FROM
forum_categories
";
$exec_cat = mysql_query($query_cat);
while($categories = mysql_fetch_assoc($exec_cat))
{
if(isset($_POST['category']))
{
$selected = ' selected';
}
else
{
$selected = '';
}
}
$this->view->assign('selected', $selected);
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$row = mysql_fetch_assoc($exec_cat);
$subject = mysql_real_escape_string(htmlentities($_POST['subject']));
$content = mysql_real_escape_string(htmlentities($_POST['content']));
$query_add_topic = "
INSERT INTO
forum_topics
(
ftDate
,fcID
,fuID
,ftSubject
,ftMessage
)
VALUES
(
NOW()
,'".$_POST['category']."'
,'".$_SESSION['userid']."'
,'".$subject."'
,'".$content."'
)
";
$exec_add_topic = mysql_query($query_add_topic);
}
else
{
while ($row = mysql_fetch_assoc($exec_cat))
{
$entries[] = $row;
$this->view->assign('entries', $entries);
}
}
And smarty
<table width=100%>
<tr>
<td>Onderwerp:</td>
</tr>
<tr>
<td width="50"><input type="text" name="subject"></td>
</tr>
<tr>
<td>Categorie type</td>
</tr>
<tr>
<td><select name="category">
{foreach from=$entries item=entry}
<option value="{$entry.fcID}"{$selected}>{$entry.fcName}</option>
{/foreach}
</select>
</td>
</tr>
<tr>
<td class="text"><textarea name="content" cols="50" rows="10"></textarea></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="send" value="Verstuur"></td>
</tr>
There is a Smarty tag for creating the
<option>tags inside a select,{html_options}. The documentation for it is here. Besides not having to build your own loop in the template, you can also specify the selected value as a parameter, which you can pass in from PHP through your $smarty object. That will let you create a<select>with minimal effort and maximum smarty goodness, easily passing in the previously selected value for your topic.