1
0
mirror of https://github.com/EGroupware/egroupware.git synced 2024-12-28 17:48:51 +01:00

Custom fields - implement ajax select widget, add year_range attribute for dates, and bug fixes

This commit is contained in:
Nathan Gray 2015-05-11 18:22:43 +00:00
commit 439e32e750
9 changed files with 346 additions and 47 deletions

View File

@ -82,8 +82,8 @@ class customfields
'float' => array('cf_len' => true), 'float' => array('cf_len' => true),
'label' => array('cf_values' => true), 'label' => array('cf_values' => true),
'select' => array('cf_len' => false, 'cf_rows' => true, 'cf_values' => true), 'select' => array('cf_len' => false, 'cf_rows' => true, 'cf_values' => true),
'date' => array('cf_len' => true, 'cf_rows' => false), 'date' => array('cf_len' => true, 'cf_rows' => false, 'cf_values' => true),
'date-time' => array('cf_len' => true, 'cf_rows' => false), 'date-time' => array('cf_len' => true, 'cf_rows' => false, 'cf_values' => true),
'select-account' => array('cf_len' => false, 'cf_rows' => true), 'select-account' => array('cf_len' => false, 'cf_rows' => true),
'htmlarea' => array('cf_len' => true, 'cf_rows' => true), 'htmlarea' => array('cf_len' => true, 'cf_rows' => true),
'button' => array('cf_values' => true), 'button' => array('cf_values' => true),
@ -300,11 +300,17 @@ class customfields
{ {
case 'delete': case 'delete':
$this->so->delete($cf_id); $this->so->delete($cf_id);
egw_framework::refresh_opener('Saved', 'admin', $cf_id /* Conflicts with accounts 'delete'*/); egw_framework::refresh_opener('Deleted', 'admin', $cf_id /* Conflicts with accounts 'delete'*/);
egw_framework::window_close(); egw_framework::window_close();
break; break;
case 'save': case 'save':
case 'apply': case 'apply':
if(!$cf_id && $this->fields[$content['cf_name']])
{
egw_framework::message(lang("Field '%1' already exists !!!",$content['cf_name']),'error');
$content['cf_name'] = '';
break;
}
if(empty($content['cf_label'])) if(empty($content['cf_label']))
{ {
$content['cf_label'] = $content['cf_name']; $content['cf_label'] = $content['cf_name'];
@ -312,11 +318,18 @@ class customfields
if (!empty($content['cf_values'])) if (!empty($content['cf_values']))
{ {
$values = array(); $values = array();
if($content['cf_values'][0] === '@')
{
$values['@'] = substr($content['cf_values'], $content['cf_values'][1] === '=' ? 2:1);
}
else
{
foreach(explode("\n",$content['cf_values']) as $line) foreach(explode("\n",$content['cf_values']) as $line)
{ {
list($var,$value) = explode('=',trim($line),2); list($var,$value) = explode('=',trim($line),2);
$var = trim($var); $var = trim($var);
$values[$var] = empty($value) ? $var : $value; $values[$var] = trim($value)==='' ? $var : $value;
}
} }
$content['cf_values'] = $values; $content['cf_values'] = $values;
} }
@ -329,6 +342,11 @@ class customfields
} }
} }
egw_customfields::update($update_content); egw_customfields::update($update_content);
if(!$cf_id)
{
$this->fields = egw_customfields::get($this->appname,true);
$cf_id = (int)$this->fields[$content['cf_name']]['id'];
}
egw_framework::refresh_opener('Saved', 'admin', $cf_id, 'edit'); egw_framework::refresh_opener('Saved', 'admin', $cf_id, 'edit');
if ($action != 'save') if ($action != 'save')
{ {
@ -370,8 +388,16 @@ class customfields
{ {
$content['cf_private'] = explode(',',$content['cf_private']); $content['cf_private'] = explode(',',$content['cf_private']);
} }
if($content['cf_name'])
{
$readonlys['cf_name'] = true;
} }
$content['cf_values'] = json_decode($content['cf_values'], true); $content['cf_values'] = json_decode($content['cf_values'], true);
}
else
{
$readonlys['button[delete]'] = true;
}
if (is_array($content['cf_values'])) if (is_array($content['cf_values']))
{ {
$values = ''; $values = '';
@ -410,17 +436,10 @@ class customfields
$content['statustext'] = $content['options'][$content['cf_type']]; $content['statustext'] = $content['options'][$content['cf_type']];
$content['attributes'] = self::$type_attribute_flags; $content['attributes'] = self::$type_attribute_flags;
// Start disabled, but don't set read-only as that changes the widget to readonly
$this->tmpl->setElementAttribute('cf_len', 'disabled', true);
$this->tmpl->setElementAttribute('cf_rows', 'disabled', true);
foreach(array('cf_len','cf_rows','cf_values') as $field)
{
$this->tmpl->setElementAttribute($field, 'disabled', !self::$type_attribute_flags[$content['cf_type']][$field]);
}
$this->tmpl->exec('admin.customfields.edit',$content,$sel_options,$readonlys,array( $this->tmpl->exec('admin.customfields.edit',$content,$sel_options,$readonlys,array(
'cf_id' => $cf_id, 'cf_id' => $cf_id,
'cf_app' => $this->appname, 'cf_app' => $this->appname,
'cf_name' => $content['cf_name'],
'use_private' => $this->use_private, 'use_private' => $this->use_private,
),2); ),2);
} }

View File

@ -797,9 +797,9 @@ app.classes.admin = AppJS.extend(
cf_type_change: function(e,widget) { cf_type_change: function(e,widget) {
var root = widget.getRoot(); var root = widget.getRoot();
var attributes = widget.getArrayMgr('content').getEntry('attributes['+widget.getValue()+']')||{}; var attributes = widget.getArrayMgr('content').getEntry('attributes['+widget.getValue()+']')||{};
root.getWidgetById('cf_values').set_statustext(widget.egw().lang(widget.getArrayMgr('content').getEntry('options['+widget.getValue()+']'))||''); root.getWidgetById('cf_values').set_statustext(widget.egw().lang(widget.getArrayMgr('content').getEntry('options['+widget.getValue()+']')||''));
root.getWidgetById('cf_len').set_disabled(!attributes.cf_len); jQuery(root.getWidgetById('cf_len').getDOMNode()).toggle(attributes.cf_len && true);
root.getWidgetById('cf_rows').set_disabled(!attributes.cf_rows); jQuery(root.getWidgetById('cf_rows').getDOMNode()).toggle(attributes.cf_rows && true);
root.getWidgetById('cf_values').set_disabled(!attributes.cf_values); jQuery(root.getWidgetById('cf_values').getParentDOMNode()).toggle(attributes.cf_values && true);
} }
}); });

View File

@ -61,7 +61,7 @@
<button statustext="Apply the changes" label="Apply" id="button[apply]" image="apply" background_image="1"/> <button statustext="Apply the changes" label="Apply" id="button[apply]" image="apply" background_image="1"/>
<button statustext="leave without saveing the entry" label="Cancel" id="button[cancel]" onclick="window.close();" image="cancel" background_image="1"/> <button statustext="leave without saveing the entry" label="Cancel" id="button[cancel]" onclick="window.close();" image="cancel" background_image="1"/>
</hbox> </hbox>
<button align="right" statustext="delete this entry" label="Delete" id="button[delete]" image="delete" background_image="1" span="all"/> <button align="right" statustext="delete this entry" label="Delete" id="button[delete]" image="delete" onclick="et2_dialog.confirm(widget,'Delete this entry?','Delete')" background_image="1" span="all"/>
</row> </row>
</rows> </rows>
</grid> </grid>

View File

@ -0,0 +1,70 @@
<?php
/**
* EGroupware - eTemplate serverside ajax select widget
*
* @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
* @package etemplate
* @subpackage api
* @link http://www.egroupware.org
* @author Nathan Gray
* @copyright 2015 Nathan Gray
* @version $Id$
*/
/**
* eTemplate ajax select widget
*
*/
class etemplate_widget_ajax_select extends etemplate_widget_menupopup
{
/**
* Fill type options in self::$request->sel_options to be used on the client
*
* @param string $cname
* @param array $expand values for keys 'c', 'row', 'c_', 'row_', 'cont'
*/
public function beforeSendToClient($cname, array $expand=null)
{
$matches = null;
if ($cname == '$row') // happens eg. with custom-fields: $cname='$row', this->id='#something'
{
$form_name = $this->id;
}
// happens with fields in nm-header: $cname='nm', this->id='${row}[something]' or '{$row}[something]'
elseif (preg_match('/(\${row}|{\$row})\[([^]]+)\]$/', $this->id, $matches))
{
$form_name = $matches[2];
}
// happens in auto-repeat grids: $cname='', this->id='something[{$row}]'
elseif (preg_match('/([^[]+)\[({\$row})\]$/', $this->id, $matches))
{
$form_name = $matches[1];
}
// happens with autorepeated grids: this->id='some[$row_cont[thing]][else]' --> just use 'else'
elseif (preg_match('/\$row.*\[([^]]+)\]$/', $this->id, $matches))
{
$form_name = $matches[1];
}
else
{
$form_name = self::form_name($cname, $this->id, $expand);
}
// Make sure &nbsp;s, etc. are properly encoded when sent, and not double-encoded
$options = (isset(self::$request->sel_options[$form_name]) ? $form_name : $this->id);
if(is_array(self::$request->sel_options[$options]))
{
// Fix any custom options from application
self::fix_encoded_options(self::$request->sel_options[$options],true);
if(!self::$request->sel_options[$options])
{
unset(self::$request->sel_options[$options]);
}
}
}
}
etemplate_widget::registerWidget('etemplate_widget_ajax_select', array('ajax_select'));

View File

@ -277,6 +277,8 @@ class etemplate_widget_customfields extends etemplate_widget_transformer
case 'date': case 'date':
case 'date-time': case 'date-time':
$widget->attrs['dataformat'] = $type == 'date' ? 'Y-m-d' : 'Y-m-d H:i:s'; $widget->attrs['dataformat'] = $type == 'date' ? 'Y-m-d' : 'Y-m-d H:i:s';
if($field['values']['min']) $widget->attrs['min'] = $field['values']['min'];
if($field['values']['max']) $widget->attrs['min'] = $field['values']['max'];
break; break;
case 'link-to': case 'link-to':
@ -287,7 +289,7 @@ class etemplate_widget_customfields extends etemplate_widget_transformer
break; break;
default: default:
if (substr($type, 0, 7) !== 'select-') break; if (substr($type, 0, 7) !== 'select-' && $type != 'ajax_select') break;
// fall-through for all select-* widgets // fall-through for all select-* widgets
case 'select': case 'select':
$this->attrs['multiple'] = $field['rows'] > 1; $this->attrs['multiple'] = $field['rows'] > 1;

View File

@ -162,6 +162,44 @@ class etemplate_widget_date extends etemplate_widget_transformer
{ {
$date = new egw_time($value); $date = new egw_time($value);
} }
if (!empty($this->attrs['min']))
{
if(is_numeric($this->attrs['min']))
{
$min = new egw_time(strtotime( $this->attrs['min'] . 'days'));
}
else
{
$min = new egw_time(strtotime($this->attrs['min']));
}
if($value < $min)
{
self::set_validation_error($form_name,lang(
"Value has to be at least '%1' !!!",
$min->format($this->type != 'date')
),'');
$value = $min;
}
}
if (!empty($this->attrs['max']))
{
if(is_numeric($this->attrs['max']))
{
$max = new egw_time(strtotime( $this->attrs['max'] . 'days'));
}
else
{
$max = new egw_time(strtotime($this->attrs['max']));
}
if($value < $max)
{
self::set_validation_error($form_name,lang(
"Value has to be at maximum '%1' !!!",
$max->format($this->type != 'date')
),'');
$value = $max;
}
}
if(!$value) if(!$value)
{ {
// Not null, blank // Not null, blank

View File

@ -233,6 +233,16 @@ var et2_customfields_list = et2_valueWidget.extend([et2_IDetachedDOM, et2_IInput
} }
this.rows[id] = cf[0]; this.rows[id] = cf[0];
// Set any additional attributes set in options, but not for widgets that pass actual options
if(['select','radio','radiogroup','checkbox','button'].indexOf(field.type) == -1 && !jQuery.isEmptyObject(field.values))
{
var w = et2_registry[attrs.type ? attrs.type : field.type];
for(var attr_name in field.values)
{
if (typeof w.prototype.attributes[attr_name] != "undefined")
attrs[attr_name] = field.values[attr_name];
}
}
// Create widget // Create widget
var widget = this.widgets[field_name] = et2_createWidget(attrs.type ? attrs.type : field.type, attrs, this); var widget = this.widgets[field_name] = et2_createWidget(attrs.type ? attrs.type : field.type, attrs, this);
} }
@ -427,6 +437,17 @@ var et2_customfields_list = et2_valueWidget.extend([et2_IDetachedDOM, et2_IInput
} }
return true; return true;
}, },
_setup_ajax_select: function(field_name, field, attrs) {
var attributes = ['get_rows','get_title','id_field','template'];
for(var i = 0; i < attributes.length; i++)
{
if(typeof field.values[attributes[i]] !== 'undefined')
{
attrs[attributes[i]] = field.values[attributes[i]];
}
}
return true;
},
_setup_float: function(field_name, field, attrs) { _setup_float: function(field_name, field, attrs) {
// No label on the widget itself // No label on the widget itself
delete(attrs.label); delete(attrs.label);

View File

@ -36,7 +36,7 @@ var et2_ajaxSelect = et2_inputWidget.extend(
"name": "Data source", "name": "Data source",
"type": "any", "type": "any",
"default": "", "default": "",
"description": "Function to get search results." "description": "Function to get search results, either a javascript function or server-side."
}, },
'get_title': { 'get_title': {
"name": "Title function", "name": "Title function",
@ -47,7 +47,7 @@ var et2_ajaxSelect = et2_inputWidget.extend(
'id_field': { 'id_field': {
"name": "Result ID field", "name": "Result ID field",
"type": "string", "type": "string",
"default": "", "default": "value",
"description": "Which key in result sub-array to look for row ID. If omitted, the key for the row will be used." "description": "Which key in result sub-array to look for row ID. If omitted, the key for the row will be used."
}, },
'template': { 'template': {
@ -74,12 +74,6 @@ var et2_ajaxSelect = et2_inputWidget.extend(
"default": "true", "default": "true",
"description": "If readonly, widget will be text. If link is set, widget will be a link." "description": "If readonly, widget will be text. If link is set, widget will be a link."
}, },
'icon': {
"name": "Icon",
"type": "string",
"default": "",
"description": "Prevent all from looking the same. Use an icon."
},
// Pass by code only // Pass by code only
'values': { 'values': {
@ -95,9 +89,17 @@ var et2_ajaxSelect = et2_inputWidget.extend(
* *
* @memberOf et2_ajaxSelect * @memberOf et2_ajaxSelect
*/ */
init: function() { init: function(parent, attrs) {
this._super.apply(this, arguments); this._super.apply(this, arguments);
if(typeof attrs.get_rows == 'string')
{
attrs.get_rows = this.egw().link('/index.php', {
menuaction: this.options.get_rows
})
}
this.createInputWidget();
this.input = null; this.input = null;
this.createInputWidget(); this.createInputWidget();
@ -109,17 +111,73 @@ var et2_ajaxSelect = et2_inputWidget.extend(
this.input.addClass("et2_textbox"); this.input.addClass("et2_textbox");
this.setDOMNode(this.input[0]); this.setDOMNode(this.input[0]);
var widget = this;
this.input.autocomplete({
delay: 100,
source: this.options.get_rows ?
this.options.get_rows :
et2_selectbox.find_select_options(this,this.options.values),
select: function(event, ui) {
widget.value = ui.item[widget.options.id_field];
if(widget.options.get_title)
{
if(typeof widget.options.get_title == 'function')
{
widget.input.val(widget.options.get_title.call(widget.value));
}
else if (typeof widget.options.get_title == 'string')
{
// TODO: Server side callback
}
}
else
{
widget.input.val(ui.item.label);
}
// Prevent default action of setting field to the value
return false;
}
});
}, },
getValue: function() getValue: function()
{ {
if(this.options.blur && this.input.val() == this.options.blur) return ""; if(this.options.blur && this.input.val() == this.options.blur) return "";
return this._super.apply(this, arguments); return this.value;
},
set_value: function(_value)
{
this.value = _value;
if(this.input.autocomplete('instance'))
{
var source = this.input.autocomplete('option','source');
if(typeof source == 'object')
{
for(var i in source)
{
if(typeof source[i].value != 'undefined' && typeof source[i].label != 'undefined' && source[i].value === _value)
{
this.input.val(source[i].label)
}
else if (typeof source[i] == 'string')
{
this.input.val(source[_value]);
break;
}
}
}
else if(typeof source == 'function')
{
// TODO
}
}
}, },
set_blur: function(_value) { set_blur: function(_value) {
if(_value) { if(_value) {
this.input.attr("placeholder", _value + "!"); // HTML5 this.input.attr("placeholder", _value + ""); // HTML5
if(!this.input[0].placeholder) { if(!this.input[0].placeholder) {
// Not HTML5 // Not HTML5
if(this.input.val() == "") this.input.val(this.options.blur); if(this.input.val() == "") this.input.val(this.options.blur);

View File

@ -47,7 +47,31 @@ var et2_date = et2_inputWidget.extend(
"ignore": true, "ignore": true,
"description": "Date/Time format. Can be set as an options to date widget", "description": "Date/Time format. Can be set as an options to date widget",
"default": '' "default": ''
} },
year_range: {
name: "Year range",
type: "string",
default: "c-10:c+10",
description: "The range of years displayed in the year drop-down: either relative to today's year (\"-nn:+nn\"), relative to the currently selected year (\"c-nn:c+nn\"), absolute (\"nnnn:nnnn\"), or combinations of these formats (\"nnnn:-nn\"). Note that this option only affects what appears in the drop-down, to restrict which dates may be selected use the min and/or max options."
},
min: {
"name": "Minimum",
"type": "any",
"default": et2_no_init,
"description": 'Minimum allowed date. Multiple types supported:\
Date: A date object containing the minimum date.\
Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.\
String: A string in the user\'s date format, or a relative date. Relative dates must contain value and period pairs; valid periods are "y" for years, "m" for months, "w" for weeks, and "d" for days. For example, "+1m +7d" represents one month and seven days from today.'
},
max: {
"name": "Maximum",
"type": "any",
"default": et2_no_init,
"description": 'Maximum allowed date. Multiple types supported:\
Date: A date object containing the maximum date.\
Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.\
String: A string in the user\'s date format, or a relative date. Relative dates must contain value and period pairs; valid periods are "y" for years, "m" for months, "w" for weeks, and "d" for days. For example, "+1m +7d" represents one month and seven days from today.'
},
}, },
legacyOptions: ["data_format"], legacyOptions: ["data_format"],
@ -256,6 +280,70 @@ var et2_date = et2_inputWidget.extend(
return this.input_date.val() == "" ? null : this.date.getTime(); return this.input_date.val() == "" ? null : this.date.getTime();
}, },
/**
* The range of years displayed in the year drop-down: either relative
* to today's year ("-nn:+nn"), relative to the currently selected year
* ("c-nn:c+nn"), absolute ("nnnn:nnnn"), or combinations of these formats
* ("nnnn:-nn"). Note that this option only affects what appears in the
* drop-down, to restrict which dates may be selected use the min_date
* and/or max_date options.
* @param {string} _value
*/
set_year_range: function(_value)
{
if(this.input_date)
{
this.input_date.datepicker('option','yearRange',_value);
}
this.options.year_range = _value;
},
/**
* Set the minimum allowed date
*
* The minimum selectable date. When set to null, there is no minimum.
* Multiple types supported:
* Date: A date object containing the minimum date.
* Number: A number of days from today. For example 2 represents two days
* from today and -1 represents yesterday.
* String: A string in the format defined by the dateFormat option, or a
* relative date. Relative dates must contain value and period pairs;
* valid periods are "y" for years, "m" for months, "w" for weeks, and
* "d" for days. For example, "+1m +7d" represents one month and seven
* days from today.
* @param {Date|Number|String} _value
*/
set_min: function(_value) {
if(this.input_date)
{
this.input_date.datepicker('option','minDate',_value);
}
this.options.min = _value;
},
/**
* Set the maximum allowed date
*
* The maximum selectable date. When set to null, there is no maximum.
* Multiple types supported:
* Date: A date object containing the maximum date.
* Number: A number of days from today. For example 2 represents two days
* from today and -1 represents yesterday.
* String: A string in the format defined by the dateFormat option, or a
* relative date. Relative dates must contain value and period pairs;
* valid periods are "y" for years, "m" for months, "w" for weeks, and
* "d" for days. For example, "+1m +7d" represents one month and seven
* days from today.
* @param {Date|Number|String} _value
*/
set_max: function(_value) {
if(this.input_date)
{
this.input_date.datepicker('option','maxDate',_value);
}
this.options.max = _value;
},
/** /**
* Setting date * Setting date
* *
@ -792,7 +880,10 @@ var et2_date_ro = et2_valueWidget.extend([et2_IDetachedDOM],
"data_format": { "data_format": {
"ignore": true, "ignore": true,
"description": "Format data is in. This is not used client-side because it's always a timestamp client side." "description": "Format data is in. This is not used client-side because it's always a timestamp client side."
} },
min: {ignore: true},
max: {ignore: true},
year_range: {ignore: true}
}, },
legacyOptions: ["data_format"], legacyOptions: ["data_format"],