I'm using opencart 1.5.6 and what I'm trying to do is add a simple select with all the categories and children categories as option on product_form.tpl.
I tried add to the follow code at admin/controler/catalog/product.php:
$this->load->model('catalog/category');
$results = $this->model_catalog_category->getCategories(0);
foreach ($results as $result) {
$this->data['categories'][] = array(
'category_id' => $result['category_id'],
'name' => $result['name']
);
}
and for the view admin/view/catalog/product_form.tpl:
<tr>
<td>Categories</td>
<td><select>
<option value="">All Categories</option>
<?php foreach ($categories as $category) { ?>
<option value="<?php echo $category['name']; ?>"><?php echo $category['name']; ?></option>
<?php } ?>
</select>
</td>
</tr>
but it's not working. It returns nothing.
I wish someone could help me and tell me what I'm missing.
I think Your approach is good but one small mistake - the method getCategories()
in administration part does not receive the $parent_id
paramaters, but array $data
parameter (for sorting and filtering possibilities). So if You want to load the categories in Your product
controller, You can proceed like this (I am reusing Your code):
$this->load->model('catalog/category');
$this->data['categories'] = array();
foreach ($this->model_catalog_category->getCategories(array()) as $category) {
$this->data['categories'][] = array(
'category_id' => $category['category_id'],
'name' => $category['name']
);
}
And in Your template:
<?php if($categories) { ?>
<tr>
<td>Categories</td>
<td><select>
<option value="">All Categories</option>
<?php foreach ($categories as $category) { ?>
<option value="<?php echo $category['category_id']; ?>"><?php echo $category['name']; ?></option>
<?php } ?>
</select>
</td>
</tr>
<?php } ?>
I think this is almost the same as what You had, do not understand why it didn't work for You...
The simplest way to get a complete list of categories is to call the database directly, such as
$result = $this->db->query("
SELECT
`category_id`,
`name`
FROM
`" . DB_PREFIX. "category_description`
WHERE
`language_id` = '" . (int) $this->config->get('config_language_id') . "'
");
However these will not show the parent categories, or be in any particular order. To do that you would need to run a recursive lookup of $this->model_catalog_category->getCategories(0);
changing the 0
to the looped category_id
to find it's children, and their children