我正在寻找使用CodeIgniter和带复选框的多个过滤器参数进行搜索的好方法。为了简单起见,想象如下:
[X] T-shirts
[ ] M
[ ] L
[X] XL
[ ] Pants
[ ] M
[ ] L
[ ] XL
页面显示商店中所有可用的衣服(get_all)。您可以使用复选框来只显示t恤衫。我已经通过这种/衣服/类型/t恤走到了这一步但现在我想在t恤中显示L和XL尺寸(两个选中的复选框)。
我不使用下拉菜单,因为我希望能够同时显示各种组合,例如L号t恤和XL号裤子。
最终我希望这是一个基于AJAX的搜索,所以POST将比基于URI的搜索更好。
实现这样的东西的最好方法是什么?
创建此表单。为每个产品类型重复字段集(本例显示的是t恤衫):
<form method="post" action="url/to/find_products">
<!-- repeat for all product types -->
<fieldset>
<input type="checkbox" name="products[tshirt][active]" value="1" /> Tshirt
<fieldset>
<input type="checkbox" name="products[tshirt][size]" value="s" /> S
<input type="checkbox" name="products[tshirt][size]" value="m" /> M
<input type="checkbox" name="products[tshirt][size]" value="l" /> L
</fieldset>
</fielset>
<!-- end repeat -->
</form>
没有使用'active'键,但它确保在没有选择选项时存在producttype键。
无论您是为每种产品类型使用单独的表,还是将它们全部放在一个表中,控制器方法都会有所不同。由于第一个比较困难,下面是:
function find_products() {
$products = $this->input->post('products');
$results = array();
foreach ($products as $product => $options) {
$table_name = $product."s";
$query = $this->db->from($table_name);
if (count($options['size']) > 0) {
$query->where_in('size', $options['size']);
}
$results = array_merge($results, $query->get());
}
return $results; # Or display view, or whatever.
}
请注意:这是非常不安全的。请确保用户的输入是有效的