Add an exclude attribute to the categories form field type, so that a developer can use the form field type and be able to exclude one or more categories from the list. In particular, most often one has, at least, an "Uncategorized" category, and may not want that showing up in a category list of the form field. In my case, I have event categories: Uncategorized, Meals, Trainings, Shifts. I do not want "Uncategorized" to be listed.
Here is my custom field that accomplishes this suggestion:
element['exclude']; // Only filter if exclude attribute is set if (!empty($excludeAttr)) { $excludedCategoryIds = array_map('intval', array_filter(array_map('trim', explode(',', $excludeAttr)))); if (!empty($excludedCategoryIds)) { $options = array_filter($options, function($option) use ($excludedCategoryIds) { return !in_array($option->value, $excludedCategoryIds); }); } } return $options; } }| Labels |
Removed:
?
|
||
| Labels |
Added:
No Code Attached Yet
|
||
| Labels |
Added:
Feature
|
||
This feature is for the developer, not end user. The end user doesn't decide if the form field can allow multiple selections either. The categories to exclude would be chosen by the developer via its ID. In my case, I'm excluding "Uncategorized" (ID 17). So my calendar app let's users pick event categories meals, trainings, and shifts, but not uncategorized.
I can post core code. I just posted my custom field as an example.
I believe this would be the correct code:
protected function getOptions()
{
$options = [];
$published = (string) $this->element['published'] ?: [];
$name = (string) $this->element['name'];
$extension = (string) $this->element['extension'];
$exclude = (string) $this->element['exclude'];
// ... existing code ...
// Prepare excluded categories array
$excludedIds = [];
if (!empty($exclude)) {
$excludedIds = array_map('intval', array_map('trim', explode(',', $exclude)));
$excludedIds = array_filter($excludedIds); // Remove any zero values
}
// ... existing code ...
// After getting categories, filter out excluded ones
if (!empty($excludedIds) && !empty($options)) {
$options = array_filter($options, function($option) use ($excludedIds) {
return !in_array((int) $option->value, $excludedIds, true);
});
}
return $options;
}
// ... existing code ...
```
------------------------------
Usage:
```
<field
name="catid"
type="categories"
extension="com_content"
label="JGLOBAL_CATEGORY"
exclude="1,5,12"
class="inputbox"
/>
```
| Status | New | ⇒ | Closed |
| Closed_Date | 0000-00-00 00:00:00 | ⇒ | 2026-01-12 08:31:04 |
| Closed_By | ⇒ | alikon |
How would you select categories to be excluded? Users cannot change the code of a field and add category_ids to exclude..
When we select categories we use the list-fancy-select layout and choose only the categories we want. Is this not applicable for you?