Advertisement
lordjackson

TDatagridTables

Feb 23rd, 2015
613
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 22.82 KB | None | 0 0
  1. <?php
  2.  
  3. Namespace Adianti\Widget\Datagrid;
  4.  
  5. use Adianti\Control\TAction;
  6. use Adianti\Core\AdiantiCoreTranslator;
  7. use Adianti\Widget\Container\TTable;
  8. use Adianti\Widget\Util\TDropDown;
  9. use Adianti\Widget\Base\TElement;
  10. use Adianti\Widget\Base\TScript;
  11. use Adianti\Widget\Util\TImage;
  12. use Exception;
  13.  
  14. /**
  15.  * DataGrid Widget: Allows to create datagrids with rows, columns and actions
  16.  *
  17.  * @version    2.0
  18.  * @package    widget
  19.  * @subpackage datagrid
  20.  * @author     Pablo Dall'Oglio
  21.  * @copyright  Copyright (c) 2006-2014 Adianti Solutions Ltd. (http://www.adianti.com.br)
  22.  * @license    http://www.adianti.com.br/framework-license
  23.  */
  24. class TDatagridTables extends TTable {
  25.  
  26.     protected $columns;
  27.     protected $actions;
  28.     protected $action_groups;
  29.     protected $rowcount;
  30.     protected $tbody;
  31.     protected $height;
  32.     protected $scrollable;
  33.     protected $modelCreated;
  34.     protected $pageNavigation;
  35.     protected $defaultClick;
  36.     protected $groupColumn;
  37.     protected $groupContent;
  38.     protected $groupMask;
  39.     protected $popover;
  40.     protected $poptitle;
  41.     protected $popcontent;
  42.     protected $objects;
  43.  
  44.     /**
  45.      * Class Constructor
  46.      */
  47.     public function __construct() {
  48.         parent::__construct();
  49.         $this->modelCreated = FALSE;
  50.         $this->defaultClick = TRUE;
  51.         $this->popover = FALSE;
  52.         $this->groupColumn = NULL;
  53.         $this->groupContent = NULL;
  54.         $this->groupMask = NULL;
  55.         $this->actions = array();
  56.         $this->action_groups = array();
  57.         //$this->{'class'} = 'display nowrap';
  58.         $this->{'class'} = 'display responsive nowrap';
  59.         $this->{'id'} = 'example';
  60.         $this->cellspacing = '0';
  61.         $this->width = '100%';
  62.        
  63.          $script =new TElement('script');
  64.         $script->type = 'text/javascript';
  65.         $script->add('
  66.           $(document).ready(function() {
  67.            $(\"#example\").dataTable();
  68.             } );
  69.        ');
  70.        
  71.     }
  72.  
  73.     /**
  74.      * Enable popover
  75.      * @param $title Title
  76.      * @param $content Content
  77.      */
  78.     public function enablePopover($title, $content) {
  79.         $this->popover = TRUE;
  80.         $this->poptitle = $title;
  81.         $this->popcontent = $content;
  82.     }
  83.  
  84.     /**
  85.      * Make the datagrid scrollable
  86.      */
  87.     public function makeScrollable() {
  88.         $this->scrollable = TRUE;
  89.     }
  90.  
  91.     /**
  92.      * disable the default click action
  93.      */
  94.     public function disableDefaultClick() {
  95.         $this->defaultClick = FALSE;
  96.     }
  97.  
  98.     /**
  99.      * Define the Height
  100.      * @param $height An integer containing the height
  101.      */
  102.     function setHeight($height) {
  103.         $this->height = $height;
  104.     }
  105.  
  106.     /**
  107.      * Add a Column to the DataGrid
  108.      * @param $object A TDataGridColumn object
  109.      */
  110.     public function addColumn(TDataGridColumn $object) {
  111.         if ($this->modelCreated) {
  112.             throw new Exception(AdiantiCoreTranslator::translate('You must call ^1 before ^2', __METHOD__, 'createModel'));
  113.         } else {
  114.             $this->columns[] = $object;
  115.         }
  116.     }
  117.  
  118.     /**
  119.      * Add an Action to the DataGrid
  120.      * @param $object A TDataGridAction object
  121.      */
  122.     public function addAction(TDataGridAction $object) {
  123.         if (!$object->getField()) {
  124.             throw new Exception(AdiantiCoreTranslator::translate('You must define the field for the action (^1)', $object->toString()));
  125.         }
  126.  
  127.         if ($this->modelCreated) {
  128.             throw new Exception(AdiantiCoreTranslator::translate('You must call ^1 before ^2', __METHOD__, 'createModel'));
  129.         } else {
  130.             $this->actions[] = $object;
  131.         }
  132.     }
  133.  
  134.     /**
  135.      * Add an Action Group to the DataGrid
  136.      * @param $object A TDataGridActionGroup object
  137.      */
  138.     public function addActionGroup(TDataGridActionGroup $object) {
  139.         if ($this->modelCreated) {
  140.             throw new Exception(AdiantiCoreTranslator::translate('You must call ^1 before ^2', __METHOD__, 'createModel'));
  141.         } else {
  142.             $this->action_groups[] = $object;
  143.         }
  144.     }
  145.  
  146.     public function setGroupColumn($column, $mask) {
  147.         $this->groupColumn = $column;
  148.         $this->groupMask = $mask;
  149.     }
  150.  
  151.     /**
  152.      * Clear the DataGrid contents
  153.      */
  154.     function clear() {
  155.         if ($this->modelCreated) {
  156.             // copy the headers
  157.             $copy = $this->children[0];
  158.             // reset the row array
  159.             $this->children = array();
  160.             // add the header again
  161.             $this->children[] = $copy;
  162.  
  163.             // add an empty body
  164.             $this->tbody = new TElement('tbody');
  165.             //     $this->tbody->{'class'} = 'tdatagrid_body';
  166. //            if ($this->scrollable) {
  167. //                $this->tbody->{'style'} = "height: {$this->height}px; display: block; overflow-y:scroll; overflow-x:hidden;";
  168. //            }
  169.             parent::add($this->tbody);
  170.  
  171.             // restart the row count
  172.             $this->rowcount = 0;
  173.         }
  174.     }
  175.  
  176.     /**
  177.      * Creates the DataGrid Structure
  178.      */
  179.     public function createModel() {
  180.         if (!$this->columns) {
  181.             return;
  182.         }
  183.  
  184.         $thead = new TElement('thead');
  185.         // $thead->{'class'} = 'tdatagrid_head';
  186.         parent::add($thead);
  187.  
  188.         $row = new TElement('tr');
  189. //        if ($this->scrollable) {
  190. //            $row->{'style'} = 'display:block';
  191. //        }
  192.         $thead->add($row);
  193.  
  194.         $actions_count = count($this->actions) + count($this->action_groups);
  195.  
  196.         if ($actions_count > 0) {
  197.             for ($n = 0; $n < $actions_count; $n++) {
  198.                 $cell = new TElement('th');
  199.                 $row->add($cell);
  200.                 //  $cell->add('&nbsp;');
  201.                 // $cell->{'class'} = 'tdatagrid_action';
  202.                 // $cell->width = '16px';
  203.             }
  204.  
  205.             //  $cell->{'class'} = 'tdatagrid_col';
  206.         }
  207.  
  208.         // add some cells for the data
  209.         if ($this->columns) {
  210.             // iterate the DataGrid columns
  211.             foreach ($this->columns as $column) {
  212.                 // get the column properties
  213.                 $name = $column->getName();
  214.                 //$label = '&nbsp;' . $column->getLabel() . '&nbsp;';
  215.                 $label = $column->getLabel();
  216.                 //     $align = $column->getAlign();
  217.                 $width = $column->getWidth();
  218. //                if (isset($_GET['order'])) {
  219. //                    if ($_GET['order'] == $name) {
  220. //                        $label .= '<img src="lib/adianti/images/ico_down.png">';
  221. //                    }
  222. //                }
  223.                 // add a cell with the columns label
  224.                 $cell = new TElement('th');
  225.                 $row->add($cell);
  226.                 $cell->add($label);
  227.  
  228.                 //  $cell->{'class'} = 'tdatagrid_col';
  229.                 //      $cell->align = $align;
  230. //                if ($width) {
  231. //                    $cell->width = ($width + 8) . 'px';
  232. //                }
  233.                 // verify if the column has an attached action
  234.                 if ($column->getAction()) {
  235.                     $url = $column->getAction();
  236.                     $cell->href = $url;
  237.                     $cell->generator = 'adianti';
  238.                 }
  239.             }
  240.  
  241.             if ($this->scrollable) {
  242.                 $cell = new TElement('td');
  243.                 //     $cell->{'class'} = 'tdatagrid_col';
  244.                 $row->add($cell);
  245.                 //   $cell->add('&nbsp;');
  246.                 // $cell->width = '12px';
  247.             }
  248.         }
  249.  
  250.         // add one row to the DataGrid
  251.         $this->tbody = new TElement('tbody');
  252.         //   $this->tbody->{'class'} = 'tdatagrid_body';
  253. //        if ($this->scrollable) {
  254. //            $this->tbody->{'style'} = "height: {$this->height}px; display: block; overflow-y:scroll; overflow-x:hidden;";
  255. //        }
  256.         parent::add($this->tbody);
  257.  
  258.         $this->modelCreated = TRUE;
  259.     }
  260.  
  261.     /**
  262.      * insert content
  263.      */
  264.     public function insert($position, $content) {
  265.         $this->tbody->insert($position, $content);
  266.     }
  267.  
  268.     /**
  269.      * Add an object to the DataGrid
  270.      * @param $object An Active Record Object
  271.      */
  272.     public function addItem($object) {
  273.         if ($this->modelCreated) {
  274.             if ($this->groupColumn AND ( is_null($this->groupContent) OR $this->groupContent !== $object->{$this->groupColumn} )) {
  275.                 $row = new TElement('tr');
  276.                 $row->{'class'} = 'tdatagrid_group';
  277.                 $this->tbody->add($row);
  278.                 $cell = new TElement('td');
  279.                 $cell->add($this->replace($this->groupMask, $object));
  280.                 $cell->colspan = count($this->actions) + count($this->action_groups) + count($this->columns);
  281.                 $row->add($cell);
  282.                 $this->groupContent = $object->{$this->groupColumn};
  283.             }
  284.  
  285.             // define the background color for that line
  286.             // $classname = ($this->rowcount % 2) == 0 ? 'tdatagrid_row_even' : 'tdatagrid_row_odd';
  287.  
  288.             $row = new TElement('tr');
  289.             $this->tbody->add($row);
  290.             //  $row->{'class'} = $classname;
  291.  
  292.             if ($this->actions) {
  293.                 // iterate the actions
  294.                 foreach ($this->actions as $action) {
  295.                     $this->prepareAction($action, $object); // validate action
  296.                     // get the action properties
  297.                     $label = $action->getLabel();
  298.                     $image = $action->getImage();
  299.                     $condition = $action->getDisplayCondition();
  300.  
  301.                     if (empty($condition) OR call_user_func($condition, $object)) {
  302.                         $url = $action->serialize();
  303.                         $first_url = isset($first_url) ? $first_url : $url;
  304.  
  305.                         // creates a link
  306.                         $link = new TElement('a');
  307.                         $link->href = $url;
  308.                         $link->generator = 'adianti';
  309.  
  310.                         // verify if the link will have an icon or a label
  311.                         if ($image) {
  312.                             $image_tag = new TImage($image);
  313.                             $image_tag->title = $label;
  314.                             $link->add($image_tag);
  315.                         } else {
  316.                             // add the label to the link
  317.                             $span = new TElement('span');
  318.                             $span->{'class'} = 'btn btn-default';
  319.                             $span->add($label);
  320.                             $link->add($span);
  321.                         }
  322.                     } else {
  323.                         $link = '';
  324.                     }
  325.  
  326.                     // add the cell to the row
  327.                     $cell = new TElement('td');
  328.                     $row->add($cell);
  329.                     $cell->add($link);
  330.                     //    $cell->width = '16px';
  331.                     //  $cell->{'class'} = 'tdatagrid_cell action';
  332.                 }
  333.             }
  334.  
  335.             if ($this->action_groups) {
  336.                 foreach ($this->action_groups as $action_group) {
  337.                     $actions = $action_group->getActions();
  338.                     $headers = $action_group->getHeaders();
  339.                     $separators = $action_group->getSeparators();
  340.  
  341.                     if ($actions) {
  342.                         $dropdown = new TDropDown($action_group->getLabel(), $action_group->getIcon());
  343.                         $last_index = 0;
  344.                         foreach ($actions as $index => $action) {
  345.                             // add intermediate headers and separators
  346.                             for ($n = $last_index; $n < $index; $n++) {
  347.                                 if (isset($headers[$n])) {
  348.                                     $dropdown->addHeader($headers[$n]);
  349.                                 }
  350.                                 if (isset($separators[$n])) {
  351.                                     $dropdown->addSeparator();
  352.                                 }
  353.                             }
  354.                             // get the action properties
  355.                             $label = $action->getLabel();
  356.                             $image = $action->getImage();
  357.                             $condition = $action->getDisplayCondition();
  358.                             if (empty($condition) OR call_user_func($condition, $object)) {
  359.                                 $this->prepareAction($action, $object); // validate action
  360.                                 $url = $action->serialize();
  361.                                 $first_url = isset($first_url) ? $first_url : $url;
  362.                                 $dropdown->addAction($label, $action, $image);
  363.                             }
  364.                             $last_index = $index;
  365.                         }
  366.                         // add the cell to the row
  367.                         $cell = new TElement('td');
  368.                         $row->add($cell);
  369.                         $cell->add($dropdown);
  370.                         //   $cell->{'class'} = 'tdatagrid_cell action';
  371.                     }
  372.                 }
  373.             }
  374.  
  375.             if ($this->columns) {
  376.                 // iterate the DataGrid columns
  377.                 foreach ($this->columns as $column) {
  378.                     // get the column properties
  379.                     $name = $column->getName();
  380.                     $align = $column->getAlign();
  381.                     $width = $column->getWidth();
  382.                     $function = $column->getTransformer();
  383.                     $content = $object->$name;
  384.                     $data = is_null($content) ? '' : $content;
  385.                     // verify if there's a transformer function
  386.                     if ($function) {
  387.                         // apply the transformer functions over the data
  388.                         $data = call_user_func($function, $data, $object, $row);
  389.                     }
  390.  
  391.                     if ($editaction = $column->getEditAction()) {
  392.                         $editaction_field = $editaction->getField();
  393.                         $div = new TElement('div');
  394.                         $div->{'class'} = 'inlineediting';
  395.                         $div->{'style'} = 'padding-left:5px;padding-right:5px';
  396.                         $div->{'action'} = $editaction->serialize();
  397.                         $div->{'field'} = $name;
  398.                         $div->{'key'} = isset($object->{$editaction_field}) ? $object->{$editaction_field} : NULL;
  399.                         $div->add($data);
  400.                         $cell = new TElement('td');
  401.                         $row->add($cell);
  402.                         $cell->add($div);
  403.                         //  $cell->{'class'} = 'tdatagrid_cell';
  404.                     } else {
  405.                         // add the cell to the row
  406.                         $cell = new TElement('td');
  407.                         $row->add($cell);
  408.                         $cell->add($data);
  409.                         //  $cell->{'class'} = 'tdatagrid_cell';
  410.                         $cell->align = $align;
  411.  
  412.                         if (isset($first_url) AND $this->defaultClick) {
  413.                             $cell->href = $first_url;
  414.                             $cell->generator = 'adianti';
  415.                             //   $cell->{'class'} = 'tdatagrid_cell';
  416.                         }
  417.                     }
  418.                     if ($width) {
  419.                         $cell->width = $width . 'px';
  420.                     }
  421.                 }
  422.             }
  423.  
  424.             if ($this->popover) {
  425.                 $data = method_exists($object, 'toArray') ? $object->toArray() : (array) $object;
  426.                 $poptitle = $this->poptitle;
  427.                 $popcontent = $this->popcontent;
  428.                 foreach ($data as $property => $value) {
  429.                     $poptitle = str_replace('{' . $property . '}', $value, $poptitle);
  430.                     $popcontent = str_replace('{' . $property . '}', $value, $popcontent);
  431.                 }
  432.  
  433.                 $row->popover = 'true';
  434.                 $row->poptitle = $poptitle;
  435.                 $row->popcontent = $popcontent;
  436.             }
  437.  
  438.             $this->objects[$this->rowcount] = $object;
  439.  
  440.             // increments the row counter
  441.             $this->rowcount ++;
  442.  
  443.             return $row;
  444.         } else {
  445.             throw new Exception(AdiantiCoreTranslator::translate('You must call ^1 before ^2', 'createModel', __METHOD__));
  446.         }
  447.     }
  448.  
  449.     /**
  450.      * Replace a string with object properties within {pattern}
  451.      * @param $content String with pattern
  452.      * @param $object  Any object
  453.      */
  454.     private function replace($content, $object) {
  455.         if (preg_match_all('/\{(.*?)\}/', $content, $matches)) {
  456.             foreach ($matches[0] as $match) {
  457.                 $property = substr($match, 1, -1);
  458.                 $content = str_replace($match, $object->$property, $content);
  459.             }
  460.         }
  461.  
  462.         return $content;
  463.     }
  464.  
  465.     /**
  466.      * Find the row index by object attribute
  467.      * @param $attribute Object attribute
  468.      * @param $value Object value
  469.      */
  470.     public function getRowIndex($attribute, $value) {
  471.         foreach ($this->objects as $pos => $object) {
  472.             if ($object->$attribute == $value) {
  473.  
  474.                 return $pos;
  475.             }
  476.         }
  477.         return NULL;
  478.     }
  479.  
  480.     /**
  481.      * Return the row by position
  482.      * @param $position Row position
  483.      */
  484.     public function getRow($position) {
  485.         return $this->tbody->get($position);
  486.     }
  487.  
  488.     /**
  489.      * Prepare action for use
  490.      * @param $action TAction
  491.      * @param $object Data Object
  492.      */
  493.     private function prepareAction(TAction $action, $object) {
  494.         $field = $action->getField();
  495.  
  496.         if (is_null($field)) {
  497.             throw new Exception(AdiantiCoreTranslator::translate('Field for action ^1 not defined', $label) . '.<br>' .
  498.             AdiantiCoreTranslator::translate('Use the ^1 method', 'setField' . '()') . '.');
  499.         }
  500.  
  501.         if (!isset($object->$field)) {
  502.             throw new Exception(AdiantiCoreTranslator::translate('Field ^1 not exists', $field));
  503.         }
  504.  
  505.         // get the object property that will be passed ahead
  506.         $key = isset($object->$field) ? $object->$field : NULL;
  507.         $action->setParameter('key', $key);
  508.  
  509.         $fieldfk = $action->getFk();
  510.         if (isset($fieldfk)) {
  511.             if (!isset($object->$fieldfk)) {
  512.                 throw new Exception(AdiantiCoreTranslator::translate('FK ^1 not exists', $field));
  513.             }
  514.             $fk = isset($object->$fieldfk) ? $object->$fieldfk : NULL;
  515.             $action->setParameter('fk', $fk);
  516.         }
  517.  
  518.         $fielddid = $action->getDid();
  519.         if (isset($fielddid)) {
  520.             if (!isset($object->$fielddid)) {
  521.                 throw new Exception(AdiantiCoreTranslator::translate('DID ^1 not exists', $fielddid));
  522.             }
  523.             $did = isset($object->$fielddid) ? $object->$fielddid : NULL;
  524.             $action->setParameter('did', $did);
  525.         }
  526.     }
  527.  
  528.     /**
  529.      * Returns the DataGrid's width
  530.      * @return An integer containing the DataGrid's width
  531.      */
  532.     public function getWidth() {
  533.         $width = 0;
  534.         if ($this->actions) {
  535.             // iterate the DataGrid Actions
  536.             foreach ($this->actions as $action) {
  537.                 $width += 22;
  538.             }
  539.         }
  540.  
  541.         if ($this->columns) {
  542.             // iterate the DataGrid Columns
  543.             foreach ($this->columns as $column) {
  544.                 $width += $column->getWidth();
  545.             }
  546.         }
  547.         return $width;
  548.     }
  549.  
  550.     /**
  551.      * Shows the DataGrid
  552.      */
  553.     function show() {
  554.         // shows the datagrid
  555.         parent::show();
  556.  
  557.         $params = $_REQUEST;
  558.         unset($params['class']);
  559.         unset($params['method']);
  560.         // to keep browsing parameters (order, page, first_page, ...)
  561.         $urlparams = '&' . http_build_query($params);
  562.  
  563.         // inline editing treatment
  564.         TScript::create('$(function() {
  565.             $(".inlineediting").editInPlace({
  566.                 callback: function(unused, enteredText)
  567.                 {
  568.                     __adianti_load_page($(this).attr("action")+"' . $urlparams . '&key="+$(this).attr("key")+"&field="+$(this).attr("field")+"&value="+encodeURIComponent(enteredText));
  569.                     return enteredText;
  570.                 },
  571.                 show_buttons: false,
  572.                 text_size:20,
  573.                 params:column=name
  574.             });
  575.        });');
  576.        
  577. //        TScript::create('
  578. //            $(document).ready(function() {
  579. //            $(\"#example\").dataTable();
  580. //          } );');
  581.            
  582.         TScript::create("
  583.          $(document).ready(function() {
  584.            var table = $(\"#example\").dataTable({
  585.                \"responsive\": true,
  586.                \"language\": {\"url\": \"app/resources/translator.txt\"},
  587.                \"dom\": \"lfrtipCT\",
  588.                \"tableTools\": {
  589.                    \"sSwfPath\": \"//cdn.datatables.net/tabletools/2.2.3/swf/copy_csv_xls_pdf.swf\",
  590.                    \"sRowSelect\": \"single\",
  591.                    \"aButtons\": [
  592.                        {
  593.                            \"sExtends\": \"print\",
  594.                            \"sButtonText\": \"Imprimir\"
  595.                        },
  596.                        {
  597.                            \"sExtends\": \"copy\",
  598.                            \"sButtonText\": \"Copiar\"
  599.                        },
  600.                        {
  601.                            \"sExtends\": \"xls\",
  602.                            \"sButtonText\": \"Exportar Excel\"
  603.                        },
  604.                        {
  605.                            \"sExtends\": \"pdf\",
  606.                            \"sPdfOrientation\": \"landscape\",
  607.                            \"sPdfMessage\": \"Associacao Municipal de Apoio Comunitario\"
  608.                        }/*,
  609.                        {
  610.                            \"sExtends\": \"collection\",
  611.                            \"sButtonText\": \"Salvar\",
  612.                            \"aButtons\": [\"csv\", \"xls\", \"pdf\"]
  613.                        }*/
  614.                    ]
  615.                },
  616.                 \"oColVis\": {
  617.                 \"buttonText\": \"Mostrar/Ocultar\",
  618.                 \"restore\": \"Restore\",
  619.                 \"showAll\": \"Show all\",
  620.                 //\"sAlign\": \"right\"
  621.                 \"aiExclude\": [0, 1]
  622.                 }
  623.            });
  624.        });
  625.        ");
  626.     }
  627.  
  628.     /**
  629.      * Assign a PageNavigation object
  630.      * @param $pageNavigation object
  631.      */
  632.     function setPageNavigation($pageNavigation) {
  633.         $this->pageNavigation = $pageNavigation;
  634.     }
  635.  
  636.     /**
  637.      * Return the assigned PageNavigation object
  638.      * @return $pageNavigation object
  639.      */
  640.     function getPageNavigation() {
  641.         return $this->pageNavigation;
  642.     }
  643.  
  644. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement