【问题标题】:Codeigniter foreach Select Menu 'Selected' OptionCodeigniter foreach 选择菜单“已选择”选项
【发布时间】:2019-07-11 06:56:27
【问题描述】:

我正在为应用程序创建主题选择选项。我希望用户从选择选项中选择他们想要的主题,浅色或深色。

我将主题名称存储在数据库中,如下所示:

然后我调用模型中的所有主题并使用以下代码返回数组:

public function getThemes() {
    $query = $this->db->query('SELECT * FROM theme');
    return $query->result_array();
}

我正在使用我的构造函数来获取数据并将其渲染到我的设置视图,如下所示:(我在 $this->data 中同时发送一些东西,这就是它在数组中的原因,但我把它删掉了代码)

$this->data = [
            'themes' => $this->model_setting->getThemes()
        ];
        $this->render('backend/standart/administrator/setting/setting_general', $this->data);

在我的 HTML 视图中,我有以下 HTML,它成功显示了正确的 2 个可用主题:

<div class="col-sm-12">
                <label>Select Your Desired Theme</label><br>
                <select class="form-control" name="site_color_theme" id="site_color_theme">
                  <?php foreach ($themes as $theme): ?>
                    <option value="<?= $theme['theme']; ?>" ><?= $theme['name']; ?></option>
                  <?php endforeach; ?>
                </select>
            </div>

当我保存设置表单时,我正在使用主题名称更新数据库中的选项表。 Html Body Class 调用此选项表并找到所选主题并使用它来呈现特定的 CSS 样式表。

我遇到的问题是当我保存我的设置时,选择选项不显示保存的主题名称以表明这是选择的活动主题。

当用户访问设置页面选择另一个主题时,如何让 Select Option 显示所选主题?

【问题讨论】:

  • 请检查您是否激活了数据库缓存。 codeigniter.com/userguide3/database/caching.html
  • The problem I am having is when I save my settings, the Select Option does not display the saved theme name to show that this is the active theme chosen: 重新加载 (F5) 页面是否适合您?如果是的话,一个简单的重定向可以为你省去很多麻烦
  • 你好 Vickel,很高兴再次见到你,我正在考虑使用简单的重定向选项哈哈,我只是更喜欢为完美而奋斗,但我感谢你的友好评论 :)

标签: database codeigniter select option


【解决方案1】:
  1. theme 表中应该有 active_theme
  2. active_theme在表单下拉site_color_theme提交时设置为1(其余主题记录设置为0
  3. 您应该使用 Codeigniter 表单助手来做到这一点:https://www.codeigniter.com/user_guide/helpers/form_helper.html#form_dropdown
// $themes = Theme list array [id => theme-name, id => theme-name]
// $active_theme = Record of "active_theme" with value equal to "1" 
// $extra = Custom HTML attributes e.g. class="something" onclick="function(js)"

echo form_dropdown('site_color_theme', $themes, $active_theme, $extra);

【讨论】:

  • 谢谢你 Murzid,Form Helper 是那里的答案;)谢谢你的支持!
猜你喜欢
  • 2011-11-16
  • 2014-11-28
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
相关资源
最近更新 更多