ListCheckbox.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php if ( ! defined( 'ABSPATH' ) ) exit;
  2. /**
  3. * Class NF_Fields_CheckboxList
  4. */
  5. class NF_Fields_ListCheckbox extends NF_Abstracts_List
  6. {
  7. protected $_name = 'listcheckbox';
  8. protected $_type = 'listcheckbox';
  9. protected $_nicename = 'Checkbox List';
  10. protected $_section = 'common';
  11. protected $_icon = 'list';
  12. protected $_templates = 'listcheckbox';
  13. protected $_old_classname = 'list-checkbox';
  14. public function __construct()
  15. {
  16. parent::__construct();
  17. $this->_nicename = __( 'Checkbox List', 'ninja-forms' );
  18. add_filter( 'ninja_forms_merge_tag_calc_value_' . $this->_type, array( $this, 'get_calc_value' ), 10, 2 );
  19. }
  20. public function admin_form_element( $id, $value )
  21. {
  22. $form_id = get_post_meta( absint( $_GET[ 'post' ] ), '_form_id', true );
  23. $field = Ninja_Forms()->form( $form_id )->get_field( $id );
  24. $list = '';
  25. foreach( $field->get_setting( 'options' ) as $option ){
  26. $checked = '';
  27. if( is_array( $value ) && in_array( $option[ 'value' ], $value ) ) $checked = "checked";
  28. $list .= "<li><label><input type='checkbox' value='{$option[ 'value' ]}' name='fields[$id][]' $checked> {$option[ 'label' ]}</label></li>";
  29. }
  30. return "<input type='hidden' name='fields[$id]' value='0' ><ul>$list</ul>";
  31. }
  32. public function get_calc_value( $value, $field )
  33. {
  34. $selected = explode( ',', $value );
  35. $value = 0;
  36. if( isset( $field[ 'options' ] ) ) {
  37. foreach ($field['options'] as $option ) {
  38. if( ! isset( $option[ 'value' ] ) || ! in_array( $option[ 'value' ], $selected ) || ! isset( $option[ 'calc' ] ) ) continue;
  39. $value += $option[ 'calc' ];
  40. }
  41. }
  42. return $value;
  43. }
  44. }