Skip to content

Generatic List Generator

World Wide Web Server edited this page Jul 4, 2012 · 25 revisions

[b]Title should be "Generic List Generator with templating"[/b]

After having rewritten the same function for different controllers and only changing minor things within the function itself, I finally got round to creating a helperfunction that does the trick. This helper should be able to generate just about any list you might want, whether it be a UL, OL, /, table or a Script.aculo.us inPlaceCollectionEditor list.

The helper is tested but not yet fully. I created a thread in the forums, and added [url=http://codeigniter.com/forums/viewreply/490938/]some examples in the 3rd post[/url].

This helper contains one function: [b][i]string[/i] generate_list([i]array/object[/i] $resource, [i]array[/i] $options, [i]string[/i] $template)[/b]

[b][i]array/object[/i] $resource[/b] Takes either an array or an object and uses it as the data for its list, it can contain arrays which it will either accept as an associative array (to create a single entry with multiple parameters) or just multiple values to create a sublist which will be nested.

[b][i]array[/i] $options[/b] Takes the following values:

  • [i]int[/i] level (defaults to 0) Keeps track of the level, the toplist gets 0 and a nested list gets 1, a list nested in the nested list gets 2, etc...
  • [i]string[/i] indent (defaults to '') Takes a string that will be added $option['level'] times where you put {INDENT}
  • [i]string[/i] link (defaults to '') Will be added between items, but not before the first or after the last.
  • [i]array[/i] ignore (defaults to array()) Takes an associated array where the values may be arrays. It checks each key/value in the $resource against this list if it is set and ignores any key/value(s) that match (which also ignores the children of this node).
  • [i]string[/i] template_head (defaults to '') Will be added before each list (for example
      ), can be ignored for the top list.
  • [i]string[/i] template_foot (defaults to '') Will be added after each list (for example
), can be ignored for the top list.
  • [i]array[/i] alternate (defaults to array()) Takes multiple values that will alternate to replace the {ALTERNATE} tag.
  • [i]array[/i] functions Takes an array that contains array with 2 values like this [i]array(method_name, object_name)[/i], if there's no such method in the object or the object isn't set it also checks the general namespace for a function by the method_name. When called it passes the level and the number to the called function. It replaces a tag by the function name uppercase: {METHOD_NAME}
  • The following example: [code]$this->load->helper('generate_list'); $resource_test = array(array('something'=>array('a','b','c')),'test','and something else');

    $options = array( 'template_head'=>'

      ', 'template_foot'=>'
    ', 'alternate'=>array('color: blue;', 'color: red;') );

    echo generate_list($resource_test, $options, '

  • {CONTENT}
  • ');[/code]

    Will generate (without the spaces/linebreaks): [code]

    • something
      • a
      • b
      • c
    • test
    • and something else
    [/code]

    [b]The contents of"generate_list_helper.php":[/b] [code]<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    function generate_list($resource, $options, $template) { if (is_object($resource)) $resource = get_object_vars($resource);

    // Check options, and put to default if unset
    if (!isset($options)) $options = array();
    if (!isset($options['level']))                 $options['level'] = 0;
    if (!isset($options['indent']))             $options['indent'] = '';
    if (!isset($options['link']))                 $options['link'] = '';
    if (!isset($options['ignore']))             $options['ignore'] = array();
    if (!isset($options['template_head']))         $options['template_head'] = '';
    if (!isset($options['template_foot']))         $options['template_foot'] = '';
    if (!isset($options['use_top_wrapper']))    $options['use_top_wrapper'] = true;
    if (!isset($options['alternate']))             $options['alternate'] = array();
    if (!isset($options['current_alternate']))     $options['current_alternate'] = 0;
    if (!isset($options['functions']))             $options['functions'] = array();
    
    // create options for next level
    $next_options = $options;
    $next_options['level']++;
    
    // instantiate output variable
    $output = '';
    
    // add the list header
    if ($options['level'] > 0 or $options['use_top_wrapper']) $output = $options['template_head'];
    
    // count the number of values in resource
    $resource_count = count($resource);
    
    // create the list
    foreach($resource as $item)
    {
        // create a temporary variable for each item
        $item_output = $template;
        
        // place the values in the item variable
        if (!is_array($item))
        {
            $item_output = preg_replace('/\{CONTENT\}/', $item, $item_output);
        }
        else
        {
            // check the ignore values
            if (count($options['ignore']) > 0)
            {
                foreach($options['ignore'] as $ignore => $ignore_value)
                {
                    if (is_array($ignore_value))
                    {
                        foreach ($ignore_value as $ignore_val_val)
                        {
                            if ($item[$ignore] == $ignore_val_val)
                            {
                                $item_output = '';
                            }
                        }
                    }
                    else
                    {
                        if ($item[$ignore] == $ignore_value)
                        {
                            $item_output = '';
                        }
                    }
                }
            }
            
            foreach ($item as $key => $value)
            {
                // if the value is an array, replace the first found instance of SUBS with a sublist
                if (!is_array($value))
                {
                    $item_output = preg_replace('/\{'.strtoupper($key).'\}/', $value, $item_output);
                }
                else
                {
                    if (empty($value)) $sublist = '';
                    else $sublist = generate_list($value, $next_options, $template);
                    if ($sublist != '') $sublist = $options['link'].$sublist;
                    $item_output = preg_replace('/\{SUBS\}/', $sublist, $item_output, 1);
                }
            }
            
            // replace any leftover nonexisting {SUBS}
            $item_output = preg_replace('/\{SUBS\}/', '', $item_output);
        }
        
        // check if any values were replaced, if not assume sublist, generate and continue
        if ($item_output == $template && is_array($item))
        {
            $item_output = generate_list($item, $next_options, $template);
            if ($resource_count > 1 && $item_output != '')
            {
                $item_output .= $options['link'];
                $resource_count--;
            }
            $output .= $item_output;
            continue;
        }
        
        // place the indent
        $item_output = preg_replace('/\{INDENT\}/', str_repeat($options['indent'], $options['level']), $item_output);
        
        // if there are methods set, replace their tags
        if (count($options['functions']) > 0)
        {
            foreach($options['functions'] as $function)
            {
                $ci =& get_instance();
                
                if (method_exists($ci->$function[1], $function[0]))
                {
                    $replace_value = $ci->$function[1]->$function[0]($options['level'], $options['current_alternate']);
                    $item_output = preg_replace('/\{'.strtoupper($function[0]).'\}/', $replace_value, $item_output);
                }
                elseif (function_exists($function[1]))
                {
                    $replace_value = $function[0]($options['level'], $options['current_alternate']);
                    $item_output = preg_replace('/\{'.$function[0].'\}/', $replace_value, $item_output);    
                }
            }
        }
        
        // place the alternation
        if (is_array($options['alternate']) && !empty($options['alternate']))
        {
            $alternate_max = count($options['alternate']);
            $alternate = $alternate_max;
            while($options['current_alternate'] % $alternate != 0 && $alternate > 0) $alternate--;
            $item_output = preg_replace('/\{ALTERNATE\}/', $options['alternate'][$alternate - 1], $item_output);
        }
        
        // link the items with the link only if it isn't the last item
        if ($resource_count > 1 && $item_output != '')
        {
            $item_output .= $options['link'];
        }
        
        // update the counters before next iteration
        $options['current_alternate']++;
        $resource_count--;
        
        // place the new item at the end of the current list
        $output .= $item_output;
        unset($item_output);
    }
    
    // close the list with the list footer
    if ($options['level'] > 0 or $options['use_top_wrapper']) $output .= $options['template_foot'];
    
    // ... and return the output
    return $output;
    

    }

    /* End of file generate_list_helper.php / / Location: ./system/application/helpers/generate_list_helper.php */[/code]

    Clone this wiki locally