在我的论坛中,当我添加一个主题时,我有一个包含所有可能类别的下拉列表。当我发布并且其中一个文本字段为空时会出现错误,我想将下拉列表中的选定项目保持选中状态。
我以前做过,但没有和Smarty一起做过。有人能看到我做错了什么吗?
$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);
}
}
而且聪明
<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>
有一个 Smarty 标签,用于在选择{html_options}
中创建 <option>
标签。 它的文档在这里。 除了不必在模板中构建自己的循环之外,您还可以将所选值指定为参数,您可以通过 $smarty 对象从 PHP 传入该参数。 这将使您能够以最小的努力和最大的聪明来创建一个<select>
,轻松地传入先前为您的主题选择的值。
Instead of this
<select name="category">
{foreach from=$entries item=entry}
<option value="{$entry.fcID}"{$selected}>{$entry.fcName}</option>
{/foreach}
</select>
You can use
<select name="category">
{html_options options = $entries selected = $entries.fcName}
</select>
hope so it will work for you