1 <?php
2
3 4 5 6 7 8 9 10
11 class Fieldmanager_Grid extends Fieldmanager_Field {
12
13 14 15 16
17 public $field_class = 'grid';
18
19 20 21 22
23 public $grid_sort = Null;
24
25 26 27 28
29 public $js_options = array();
30
31 32 33 34 35
36 public function __construct( $label = '', $options = array() ) {
37 $this->attributes = array(
38 'size' => '50',
39 );
40 parent::__construct( $label, $options );
41 $this->sanitize = function( $row, $col, $values ) {
42 foreach ( $values as $k => $val ) {
43 $values[$k] = sanitize_text_field( $val );
44 }
45 return $values;
46 };
47
48 fm_add_script( 'handsontable', 'js/grid/jquery.handsontable.js' );
49 fm_add_script( 'contextmenu', 'js/grid/lib/jQuery-contextMenu/jquery.contextMenu.js' );
50 fm_add_script( 'ui_position', 'js/grid/lib/jQuery-contextMenu/jquery.ui.position.js' );
51 fm_add_script( 'grid', 'js/grid.js' );
52 fm_add_style( 'context_menu_css', 'js/grid/lib/jQuery-contextMenu/jquery.contextMenu.css' );
53 fm_add_style( 'handsontable_css', 'js/grid/jquery.handsontable.css' );
54 }
55
56 57 58 59 60
61 public function form_element( $value = '' ) {
62 $grid_activate_id = 'grid-activate-' . uniqid( true );
63 if ( !empty( $value ) && is_callable( $this->grid_sort ) ) {
64 $value = call_user_func( $this->grid_sort, $value );
65 }
66 $out = sprintf(
67 '<div class="grid-toggle-wrapper">
68 <div class="fm-grid" id="%2$s" data-fm-grid-name="%1$s" data-fm-grid-opts="%3$s"></div>
69 <input name="%1$s" class="fm-element" type="hidden" value="%4$s" />
70 <p><a href="#" class="grid-activate" id="%7$s" data-with-grid-title="%6$s">%5$s</a></p>
71 </div>',
72 esc_attr( $this->get_form_name() ),
73 esc_attr( 'hot-grid-id-' . uniqid( true ) ),
74 esc_attr( wp_json_encode( $this->js_options ) ),
75 esc_attr( wp_json_encode( $value ) ),
76 esc_attr__( 'Show Data Grid', 'fieldmanager' ),
77 esc_attr__( 'Hide Data Grid', 'fieldmanager' ),
78 esc_attr( $grid_activate_id )
79 );
80 return $out;
81 }
82
83 84 85 86 87
88 public function presave( $value, $current_value = array() ) {
89 $rows = json_decode( stripslashes( $value ), TRUE );
90 if ( !is_array( $rows ) ) return array();
91 foreach ( $rows as $i => $cells ) {
92 foreach ( $cells as $k => $cell ) {
93 $cell = call_user_func( $this->sanitize, $i, $k, $cell );
94 }
95 }
96 return $rows;
97 }
98
99 }