Search code examples
expressionenginecategories

How to limit child category depth in expression engine's Control Panel?


Does anyone know if it is possible and how to limit the depth of child categories from the backend (Control Panel) in ExpressionEngine?

The idea is to allow someone to add their own category hierarchy from the Control Panel, but limiting them to 4 child categories, for instance:

All > 5 Star > Entertainment > Movies > Animated

but not this:

All > 5 Star > Entertainment > Movies > Animated > 3D

This is just an example.

Any help would be greatly appreciated.


Solution

  • No, not unless you write your own Extension to tap into EE general display hooks (the category add/edit/listing doesn't have any hooks).

    Easiest approach would be to use CP CSS JS add-on and code your own JS to prevent the selection too deep.

    Target something like $(".category_field select#parent_id") and if the category parent selection has 32 spaces (4x8) Array(33).join(" ") then don't allow the selection and move up the options until you find an option (category parent) that has less spaces (i.e. isn't as deep).

    This might work (untested)...

    $(".category_field select#parent_id").change( function() {
        var $selected = $(this).children("option:selected")
        if ($selected.text().indexOf( Array(33).join(" ") ) >= 0) {
            // Too deep
            $selected.prevAll().each(function(){
                if ($(this).text().indexOf( Array(33).join(" ") ) < 0 ) {
                    $(this).parent().children('option:selected').removeProp('selected');
                    $(this).prop('selected', true);
                    return;
                }
            });
        }
    });