public ThemeSelection(jQueryObject select) : base(select) { var self = this; this.Change(e => { jQuery.Instance.cookie("ThemePreference", select.GetValue(), new { path = Q.Config.ApplicationPath }); J("body").RemoveClass("skin-" + GetCurrentTheme()); J("body").AddClass("skin-" + select.GetValue()); }); Q.AddOption(select, "blue", Q.Text("Site.Layout.ThemeBlue")); Q.AddOption(select, "blue-light", Q.Text("Site.Layout.ThemeBlueLight")); Q.AddOption(select, "purple", Q.Text("Site.Layout.ThemePurple")); Q.AddOption(select, "purple-light", Q.Text("Site.Layout.ThemePurpleLight")); Q.AddOption(select, "red", Q.Text("Site.Layout.ThemeRed")); Q.AddOption(select, "red-light", Q.Text("Site.Layout.ThemeRedLight")); Q.AddOption(select, "green", Q.Text("Site.Layout.ThemeGreen")); Q.AddOption(select, "green-light", Q.Text("Site.Layout.ThemeGreenLight")); Q.AddOption(select, "yellow", Q.Text("Site.Layout.ThemeYellow")); Q.AddOption(select, "yellow-light", Q.Text("Site.Layout.ThemeYellowLight")); Q.AddOption(select, "black", Q.Text("Site.Layout.ThemeBlack")); Q.AddOption(select, "black-light", Q.Text("Site.Layout.ThemeBlackLight")); select.Value(GetCurrentTheme()); }
public ThemeSelection(jQueryObject select) : base(select) { var self = this; this.Change(e => { jQuery.Instance.cookie("ThemePreference", select.GetValue(), new { path = Q.Config.ApplicationPath }); J("body").RemoveClass("skin-" + GetCurrentTheme()); J("body").AddClass("skin-" + select.GetValue()); }); Q.AddOption(select, "blue", Q.Text("Site.Layout.ThemeBlue")); Q.AddOption(select, "blue-light", Q.Text("Site.Layout.ThemeBlueLight")); Q.AddOption(select, "purple", Q.Text("Site.Layout.ThemePurple")); Q.AddOption(select, "purple-light", Q.Text("Site.Layout.ThemePurpleLight")); Q.AddOption(select, "red", Q.Text("Site.Layout.ThemeRed")); Q.AddOption(select, "red-light", Q.Text("Site.Layout.ThemeRedLight")); Q.AddOption(select, "green", Q.Text("Site.Layout.ThemeGreen")); Q.AddOption(select, "green-light", Q.Text("Site.Layout.ThemeGreenLight")); Q.AddOption(select, "yellow", Q.Text("Site.Layout.ThemeYellow")); Q.AddOption(select, "yellow-light", Q.Text("Site.Layout.ThemeYellowLight")); Q.AddOption(select, "black", Q.Text("Site.Layout.ThemeBlack")); Q.AddOption(select, "black-light", Q.Text("Site.Layout.ThemeBlackLight")); select.Value(GetCurrentTheme()); }
public override bool IsValueChanged() { if (_input != null) { string valueAsString = (_defaultValue != null && _defaultValue.Value != null) ? _defaultValue.Value.ToString() : ""; return(_input.GetValue() != valueAsString); } else { return(false); } }
public override object SerializeValue() { string timeString = _input.GetValue(); if (timeString == "") { return(null); } DateTime currentDate = DateTimeEx.AddTimeToDate(_dateTimeValue, timeString); return(currentDate); }
public override object SerializeValue() { string durationString = _input.GetValue(); if (durationString == "") { return(null); } int?duration = DateTimeEx.ParseDuration(durationString); return(duration); }
// actual addTab function: adds new tab using the title input from the form above static void addTab(TabsObject tabs) { string tab_title = tab_title_input.GetValue() ?? ("Tab " + tab_counter); tabs.Tabs(TabsMethod.Add, "#tabs-" + tab_counter, tab_title); tab_counter++; }
public LanguageSelection(jQueryObject select, string currentLanguage) : base(select) { currentLanguage = currentLanguage ?? "en"; var self = this; this.Change(e => { jQuery.Instance.cookie("LanguagePreference", select.GetValue(), new { path = Q.Config.ApplicationPath }); Window.Location.Reload(true); }); Q.GetLookupAsync<LanguageRow>("Administration.Language").Then(x => { if (!x.Items.Any(z => z.LanguageId == currentLanguage)) { var idx = currentLanguage.LastIndexOf("-"); if (idx >= 0) { currentLanguage = currentLanguage.Substr(0, idx); if (!x.Items.Any(z => z.LanguageId == currentLanguage)) { currentLanguage = "en"; } } else currentLanguage = "en"; } foreach (var l in x.Items) Q.AddOption(select, l.LanguageId, l.LanguageName); select.Value(currentLanguage); }); }
public URLEditor(jQueryObject input) : base(input) { input.AddClass("url").Attribute("title", "URL 'http://www.site.com/sayfa' formatında girilmelidir."); input.Bind("blur." + this.uniqueName, delegate { var validator = input.Closest("form").GetDataValue("validator").As <jQueryValidator>(); if (validator == null) { return; } if (!input.HasClass("error")) { return; } var value = input.GetValue().TrimToNull(); if (value == null) { return; } value = "http://" + value; if (((dynamic)(jQueryValidator.Methods["url"])).apply(validator, new object[] { value, input[0] }) == true) { input.Value(value); validator.ValidateElement(input[0]); } }); }
public override void Init(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context) { // Get the text box element jQueryObject select = jQuery.FromElement(element).Find(".sparkle-input-optionset-part"); jQueryEventHandler onChangeHandler = delegate(jQueryEvent e) { Observable <OptionSetValue> observable = (Observable <OptionSetValue>)valueAccessor(); string newValue = select.GetValue(); int? newValueInt = null; if (!String.IsNullOrEmpty(newValue)) { newValueInt = int.Parse(newValue); } // Set the optionset value OptionSetValue newValueOptionSetValue = new OptionSetValue(newValueInt); newValueOptionSetValue.Name = select.Find("option:selected").GetText(); observable.SetValue(newValueOptionSetValue); }; select.Change(onChangeHandler); allBindingsAccessor()["optionsValue"] = "value"; allBindingsAccessor()["optionsText"] = "name"; OptionSetBindingOptions optionSetOptions = (OptionSetBindingOptions)((object)allBindingsAccessor()["optionSetOptions"]); // Create a value accessor for the optionset options Func <List <OptionSetItem> > optionsValueAccessor = delegate() { return(MetadataCache.GetOptionSetValues(optionSetOptions.entityLogicalName, optionSetOptions.attributeLogicalName, optionSetOptions.allowEmpty)); }; Script.Literal("ko.bindingHandlers.options.update({0},{1},{2},{3},{4})", select.GetElement(0), optionsValueAccessor, allBindingsAccessor, viewModel, context); //Script.Literal("return { controlsDescendantBindings: true };"); }
public URLEditor(jQueryObject input) : base(input) { input.AddClass("url").Attribute("title", "URL 'http://www.site.com/sayfa' formatında girilmelidir."); input.Bind("blur." + this.uniqueName, delegate { var validator = input.Closest("form").GetDataValue("validator").As<jQueryValidator>(); if (validator == null) return; if (!input.HasClass("error")) return; var value = input.GetValue().TrimToNull(); if (value == null) return; value = "http://" + value; if (((dynamic)(jQueryValidator.Methods["url"])).apply(validator, new object[] { value, input[0] }) == true) { input.Value(value); validator.ValidateElement(input[0]); } }); }
private void LoadLocalization() { var self = this; var opt = new ServiceCallOptions <RetrieveResponse <TEntity> >(); opt.Service = this.GetService() + "/RetrieveLocalization"; opt.BlockUI = true; opt.Request = new RetrieveLocalizationRequest { EntityId = this.EntityId.Value, CultureId = Int32.Parse(localizationSelect.GetValue(), 10) }; opt.OnSuccess = response => { var valueByName = new JsDictionary <string, string>(); self.localizationGrid.Load(self.Entity); self.localizationGrid.EnumerateItems((item, widget) => { if (widget.Element.Is(":input")) { valueByName[item.Name] = widget.Element.GetValue(); } }); self.localizationGrid.Load(response.Entity); self.localizationGrid.EnumerateItems((item, widget) => { if (widget.Element.Is(":input")) { var hint = valueByName[item.Name]; if (hint != null && hint.Length > 0) { widget.Element .Attribute("title", "Türkçe Metin: " + hint) .Attribute("placeholder", hint); } } }); }; Q.ServiceCall(opt); }
public QuickSearchInput(jQueryObject input, QuickSearchInputOptions opt) : base(input, opt) { input.Attribute("title", Texts.Controls.QuickSearch.Hint) .Attribute("placeholder", Texts.Controls.QuickSearch.Placeholder); lastValue = Q.Trim(input.GetValue() ?? ""); var self = this; this.element.Bind("keyup." + this.uniqueName, delegate { self.CheckIfValueChanged(); }); this.element.Bind("change." + this.uniqueName, delegate { self.CheckIfValueChanged(); }); J("<span><i></i></span>").AddClass("quick-search-icon") .InsertBefore(input); if (options.Fields != null && options.Fields.Count > 0) { var a = J("<a/>").AddClass("quick-search-field") .Attribute("title", Texts.Controls.QuickSearch.FieldSelection) .InsertBefore(input); var menu = J("<ul></ul>").CSS("width", "120px"); foreach (var item in options.Fields) { var field = item; J("<li><a/></li>").AppendTo(menu) .Children().Attribute("href", "#") .Text(item.Title ?? "") .Click(delegate(jQueryEvent e) { e.PreventDefault(); fieldChanged = self.field != field; self.field = field; UpdateInputPlaceHolder(); CheckIfValueChanged(); }); } new PopupMenuButton(a, new PopupMenuButtonOptions { PositionMy = "right top", PositionAt = "right bottom", Menu = menu }); this.field = options.Fields[0]; UpdateInputPlaceHolder(); } }
public void AddTerritoryToInput(jQueryEvent eventHandler) { jQueryObject autoSuggestBox = jQuery.Select("#TerritoriesAutoSuggest"); string[] territoryArray = autoSuggestBox.GetValue().Split(','); territoryArray[territoryArray.Length - 1] = " " + eventHandler.CurrentTarget.InnerHTML.Trim() + ", "; jQuery.Select("#TerritoriesAutoSuggest").Value(territoryArray.ToString()); }
private void OnNewItemKeyUp(jQueryEvent e) { string text = _newItem.GetValue().Trim(); if ((text.Length != 0) && (e.Which == 13)) { _todoList.CreateItem(text); _newItem.Value(String.Empty); UpdateRendering(); } }
private DateTime GetSelectedValue() { DateTime selectedValue = null; if (!_calendarOpen) { selectedValue = DateTimeEx.ParseDateSpecific(_input.GetValue(), _dateFormat); } else { selectedValue = (DateTime)_input.Plugin <DatePickerObject>().DatePicker(DatePickerMethod.GetDate); } return(selectedValue); }
public override void Init(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context) { string formatString = GetFormatString(); jQueryObject container = jQuery.FromElement(element); jQueryObject inputField = container.Find(".sparkle-input-timeofday-part"); jQueryObject selectButton = container.Find(".sparkle-input-timeofday-button-part"); AutoCompleteOptions options = XrmTimeEditor.GetTimePickerAutoCompleteOptions(formatString); options.Position = new Dictionary <string, object>("collision", "fit"); options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent) { // Note we assume that the binding has added an array of string items string value = ((Dictionary)uiEvent.Item)["value"].ToString(); TrySetObservable(valueAccessor, inputField, value); }; inputField = inputField.Plugin <AutoCompleteObject>().AutoComplete(options); // Add the click binding to show the drop down selectButton.Click(delegate(jQueryEvent e) { inputField.Plugin <AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search, ""); // Give "" to show all items }); //// Set initial value //Observable<DateTime> dateValueAccessor = (Observable<DateTime>)valueAccessor(); //DateTime intialValue = dateValueAccessor.GetValue(); //FormatterUpdate(inputField, intialValue); //handle the field changing KnockoutUtils.RegisterEventHandler(inputField.GetElement(0), "change", delegate(object sender, EventArgs e) { string value = inputField.GetValue(); TrySetObservable(valueAccessor, inputField, value); }); Action disposeCallBack = delegate() { Script.Literal("$({0}).autocomplete(\"destroy\")", element); }; //handle disposal (if KO removes by the template binding) Script.Literal("ko.utils.domNodeDisposal.addDisposeCallback({0}, {1})", element, (object)disposeCallBack); // Note: Because the time picker is always part of the date picker - we don't need to display validation messages //Knockout.BindingHandlers["validationCore"].Init(element, valueAccessor, allBindingsAccessor, null, null); }
public override void Init(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context) { // Get the text box element jQueryObject textBox = jQuery.FromElement(element).Find(".sparkle-input-textbox-part"); NumberFormatInfo format = GetNumberFormatInfo(allBindingsAccessor); jQueryEventHandler onChangeHandler = delegate(jQueryEvent e) { Observable <string> observable = (Observable <string>)valueAccessor(); string newValue = textBox.GetValue(); TrySetObservable(valueAccessor, textBox, newValue, format); }; textBox.Change(onChangeHandler); // Stop further binding //Script.Literal("return { controlsDescendantBindings: true };"); }
public override void Init(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context) { jQueryObject container = jQuery.FromElement(element); jQueryObject inputField = container.Find(".sparkle-input-duration-part"); jQueryObject selectButton = container.Find(".sparkle-input-duration-button-part"); AutoCompleteOptions options = new AutoCompleteOptions(); options.Position = new Dictionary <string, object>("collision", "fit"); options.Source = new string[] { "1 m", "2 m", "1 h", "2 h", "1 d" }; options.Delay = 0; options.MinLength = 0; options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent) { // Note we assume that the binding has added an array of string items string value = ((Dictionary)uiEvent.Item)["value"].ToString(); TrySetObservable(valueAccessor, inputField, value); }; inputField = inputField.Plugin <AutoCompleteObject>().AutoComplete(options); // Add the click binding to show the drop down selectButton.Click(delegate(jQueryEvent e) { inputField.Plugin <AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search, "");// Give "" to show all items }); //handle the field changing KnockoutUtils.RegisterEventHandler(element, "change", delegate(object sender, EventArgs e) { string value = inputField.GetValue(); TrySetObservable(valueAccessor, inputField, value); }); Action disposeCallBack = delegate() { Script.Literal("$({0}).autocomplete(\"destroy\")", element); }; //handle disposal (if KO removes by the template binding) Script.Literal("ko.utils.domNodeDisposal.addDisposeCallback({0}, {1})", element, (object)disposeCallBack); //Knockout.BindingHandlers["validationCore"].Init(element, valueAccessor, allBindingsAccessor, null, null); }
public LanguageSelection(jQueryObject select, string currentLanguage) : base(select) { currentLanguage = currentLanguage ?? "en"; var self = this; this.Change(e => { jQuery.Instance.cookie("LanguagePreference", select.GetValue(), new { path = Q.Config.ApplicationPath, expires = 365 }); Window.Location.Reload(true); }); Q.GetLookupAsync <LanguageRow>("Administration.Language").Then(x => { if (!x.Items.Any(z => z.LanguageId == currentLanguage)) { var idx = currentLanguage.LastIndexOf("-"); if (idx >= 0) { currentLanguage = currentLanguage.Substr(0, idx); if (!x.Items.Any(z => z.LanguageId == currentLanguage)) { currentLanguage = "en"; } } else { currentLanguage = "en"; } } foreach (var l in x.Items) { Q.AddOption(select, l.LanguageId, l.LanguageName); } select.Value(currentLanguage); }); }
public override void Init(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context) { jQueryObject inputField = jQuery.FromElement(element); AutoCompleteOptions options = (AutoCompleteOptions)((object)allBindingsAccessor()["autocompleteOptions"]); options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent) { // Note we assume that the binding has added an array of string items string value = ((Dictionary)uiEvent.Item)["value"].ToString(); TrySetObservable(valueAccessor, inputField, value); }; inputField = inputField.Plugin <AutoCompleteObject>().AutoComplete(options); jQueryObject selectButton = inputField.Siblings(".timeSelectButton"); // Add the click binding to show the drop down selectButton.Click(delegate(jQueryEvent e) { inputField.Plugin <AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search); }); //handle the field changing KnockoutUtils.RegisterEventHandler(element, "change", delegate(object sender, EventArgs e) { string value = inputField.GetValue(); TrySetObservable(valueAccessor, inputField, value); }); Action disposeCallBack = delegate() { Script.Literal("$({0}).autocomplete(\"destroy\")", element); }; //handle disposal (if KO removes by the template binding) Script.Literal("ko.utils.domNodeDisposal.addDisposeCallback({0}, {1})", element, (object)disposeCallBack); Knockout.BindingHandlers["validationCore"].Init(element, valueAccessor, allBindingsAccessor, null, null); }
private void RowFieldChange(jQueryObject row) { jQueryObject select = row.Children("div.f").Children("select"); string fieldName = select.GetValue(); bool isEmpty = (fieldName == null || fieldName == ""); // if a field is selected and first option is "---please select---", remove it if (!isEmpty) { OptionElement firstOption = (OptionElement)select.Children("option").First()[0]; if (firstOption.Value == null || firstOption.Value == "") { J(firstOption).Remove(); } } jQueryObject opDiv = row.Children("div.o"); jQueryObject opSelect = opDiv.Children("select"); if (opSelect.Length == 0) { opSelect = J("<select/>").AppendTo(opDiv).Change(OnRowOperatorChange); } else { Q.ClearOptions(opSelect); } RemoveFilterHandler(row); PopulateOperatorList(opSelect); RowOperatorChange(row); UpdateParens(); UpdateButtons(); }
private jQueryObject FindEmptyRow() { jQueryObject result = null; rowsDiv.Children().Each(delegate(int index, System.Html.Element row) { jQueryObject fieldSelect = J(row).Children("div.f").Children("select"); if (fieldSelect.Length == 0) { return(true); } string val = fieldSelect.GetValue(); if (val == null || val.Length == 0) { result = J(row); return(false); } return(true); }); return(result); }
private jQueryObject FindEmptyRow() { jQueryObject result = null; rowsDiv.Children().Each((index, row) => { jQueryObject fieldInput = J(row).Children("div.f").Children("input.field-select").First(); if (fieldInput.Length == 0) { return(true); } string val = fieldInput.GetValue(); if (val == null || val.Length == 0) { result = J(row); return(false); } return(true); }); return(result); }
static Manipulation() { jQuery.OnDocumentReady(delegate() { // tabs init with a custom tab template and an "add" callback filling in the content TabsObject tabs = jQuery.Select("#tabs6") .Plugin <TabsObject>() .Tabs(new TabsOptions( "tabTemplate", "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>", "add", new jQueryUIEventHandler <TabsAddEvent>( delegate(jQueryEvent @event, TabsAddEvent ui) { string tab_content = tab_content_input.GetValue() ?? ("Tab " + tab_counter + " content."); jQuery.Select(ui.Panel).Append("<p>" + tab_content + "</p>"); }))); // modal dialog init: custom buttons and a "close" callback reseting the form inside DialogObject dialog = jQuery.Select("#dialog11") .Plugin <DialogObject>() .Dialog(new DialogOptions( DialogOption.AutoOpen, false, DialogOption.Modal, true, DialogOption.Buttons, new DialogOptions( "Add", new Action(delegate() { addTab(tabs); jQuery.This.Plugin <DialogObject>().Dialog(DialogMethod.Close); }), "Cancel", new Action(delegate() { jQuery.This.Plugin <DialogObject>().Dialog(DialogMethod.Open); })), DialogMethod.Open, new Action(delegate() { tab_title_input.Focus(); }), DialogMethod.Close, new Action(delegate() { // addTab form: calls addTab function on submit and closes the dialog jQuery.Select("form", jQuery.This) .Submit(new jQueryEventHandler(delegate(jQueryEvent e) { addTab(tabs); jQuery.This.Plugin <DialogObject>().Dialog(DialogMethod.Close); e.PreventDefault(); e.StopPropagation(); })); }))); // addTab button: just opens the dialog jQuery.Select("#add_tab") .Plugin <ButtonObject>() .Button() .Click(new jQueryEventHandler(delegate(jQueryEvent e) { dialog.Dialog(DialogMethod.Open); })); // close icon: removing the tab on click // note: closable tabs gonna be an option in the future - see http://dev.jqueryui.com/ticket/3924 jQuery.Select("#tabs6 span.ui-icon-close") .Live("click", new jQueryEventHandler(delegate(jQueryEvent e) { int index = jQuery.Select("li", tabs).Index(jQuery.This.Parent()[0]); tabs.Tabs(TabsMethod.Remove, index); })); }); }
static ModalForm() { jQuery.OnDocumentReady(delegate() { jQueryObject name = jQuery.Select("#name"); jQueryObject email = jQuery.Select("#email"); jQueryObject password = jQuery.Select("#password"); jQueryObject allFields = jQuery.FromObject(new jQuery[] { }).Add(name).Add(email).Add(password); jQueryObject tips = jQuery.Select(".validateTips"); Action <string> updateTips = new Action <string>(delegate(string t) { tips.Text(t) .AddClass("ui-state-highlight"); Window.SetTimeout(new Action(delegate() { tips.RemoveClass("ui-state-highlight"); //, 1500 ); }), 500); }); Func <jQueryObject, string, int, int, bool> checkLength = new Func <jQueryObject, string, int, int, bool>( delegate(jQueryObject o, string n, int min, int max) { if (o.GetValue().Length > max || o.GetValue().Length < min) { o.AddClass("ui-state-error"); updateTips("Length of " + n + " must be between " + min + " and " + max + "."); return(false); } else { return(true); } }); Func <jQueryObject, RegularExpression, string, bool> checkRegexp = new Func <jQueryObject, RegularExpression, string, bool>( delegate(jQueryObject o, RegularExpression regexp, string n) { if (!(regexp.Test(o.GetValue()))) { o.AddClass("ui-state-error"); updateTips(n); return(false); } else { return(true); } }); jQuery.Select("#dialog-form") .Plugin <DialogObject>() .Dialog(new DialogOptions( DialogOption.AutoOpen, false, DialogOption.Height, 300, DialogOption.Width, 350, DialogOption.Modal, true, DialogOption.Buttons, new DialogOptions( "Create an account", new Action(delegate() { bool bValid = true; allFields.RemoveClass("ui-state-error"); bValid = bValid && checkLength(name, "username", 3, 16); bValid = bValid && checkLength(email, "email", 6, 80); bValid = bValid && checkLength(password, "password", 5, 16); bValid = bValid && checkRegexp(name, new RegularExpression("^[a-z]([0-9a-z_])+$"), "Username may consist of a-z, 0-9, underscores, begin with a letter."); // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/ bValid = bValid && checkRegexp(email, new RegularExpression(@"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$"), "eg. [email protected]"); bValid = bValid && checkRegexp(password, new RegularExpression("^([0-9a-zA-Z])+$"), "Password field only allow : a-z 0-9"); if (bValid) { jQuery.Select("#users tbody") .Append("<tr>" + "<td>" + name.GetValue() + "</td>" + "<td>" + email.GetValue() + "</td>" + "<td>" + password.GetValue() + "</td>" + "</tr>"); jQuery.This.Plugin <DialogObject>() .Dialog(DialogMethod.Close); } }), "Cancel", new Action(delegate() { jQuery.This.Plugin <DialogObject>() .Dialog(DialogMethod.Close); })), DialogEvents.Close, new Action(delegate() { allFields.Value("").RemoveClass("ui-state-error"); }))); jQuery.Select("#create-user") .Plugin <ButtonObject>() .Button() .Click(new jQueryEventHandler(delegate(jQueryEvent e) { jQuery.Select("#dialog-form").Plugin <DialogObject>().Dialog(DialogMethod.Open); })); }); }
public XrmLookupEditor(EditorArguments args) : base(args) { _args = args; _container = jQuery.FromHtml("<div ><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr><td><INPUT type=text class='sparkle-input-inline' /></td><td class='lookup-button-td'><input type=button class='sparkle-lookup-button' /></td></tr></table></div>"); _container.AppendTo(_args.Container); jQueryObject inputField = _container.Find(".sparkle-input-inline"); jQueryObject selectButton = _container.Find(".sparkle-lookup-button"); _input = inputField; _input.Focus().Select(); _autoComplete = inputField.Plugin <AutoCompleteObject>(); AutoCompleteOptions options = new AutoCompleteOptions(); options.MinLength = 100000; options.Delay = 0; // TODO- set to something that makes sense bool justSelected = false; options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent) { if (_value == null) { _value = new EntityReference(null, null, null); } // Note we assume that the binding has added an array of string items AutoCompleteItem item = (AutoCompleteItem)uiEvent.Item; string value = item.Label; _input.Value(value); _value.Id = ((EntityReference)item.Value).Id; _value.Name = ((EntityReference)item.Value).Name; _value.LogicalName = ((EntityReference)item.Value).LogicalName; justSelected = true; Script.Literal("return false;"); }; // options.Focus = delegate(jQueryEvent e, AutoCompleteFocusEvent uiEvent) { // Prevent the value being updated in the text box we scroll through the results Script.Literal("return false;"); }; XrmLookupEditorOptions editorOptions = (XrmLookupEditorOptions)args.Column.Options; // wire up source to CRM search Action <AutoCompleteRequest, Action <AutoCompleteItem[]> > queryDelegate = delegate(AutoCompleteRequest request, Action <AutoCompleteItem[]> response) { // Get the option set values editorOptions.queryCommand(request.Term, delegate(EntityCollection fetchResult) { AutoCompleteItem[] results = new AutoCompleteItem[fetchResult.Entities.Count]; for (int i = 0; i < fetchResult.Entities.Count; i++) { results[i] = new AutoCompleteItem(); results[i].Label = (string)fetchResult.Entities[i].GetAttributeValue(editorOptions.nameAttribute); EntityReference id = new EntityReference(null, null, null); id.Name = results[i].Label; id.LogicalName = fetchResult.Entities[i].LogicalName; id.Id = (Guid)fetchResult.Entities[i].GetAttributeValue(editorOptions.idAttribute); results[i].Value = id; string typeCodeName = fetchResult.Entities[i].LogicalName; // Get the type code from the name to find the icon if (!string.IsNullOrEmpty(editorOptions.typeCodeAttribute)) { typeCodeName = fetchResult.Entities[i].GetAttributeValue(editorOptions.typeCodeAttribute).ToString(); } results[i].Image = MetadataCache.GetSmallIconUrl(typeCodeName); } response(results); // Disable it now so typing doesn't trigger a search AutoCompleteOptions disableOption = new AutoCompleteOptions(); disableOption.MinLength = 100000; _autoComplete.AutoComplete(disableOption); }); }; options.Source = queryDelegate; inputField = _autoComplete.AutoComplete(options); ((RenderItemDelegate)Script.Literal("{0}.data('ui-autocomplete')", inputField))._renderItem = delegate(object ul, AutoCompleteItem item) { return((object)jQuery.Select("<li>").Append("<a class='sparkle-menu-item'><span class='sparkle-menu-item-img'><img src='" + item.Image + "'/></span><span class='sparkle-menu-item-label'>" + item.Label + "</span></a>").AppendTo((jQueryObject)ul)); }; // Add the click binding to show the drop down selectButton.Click(delegate(jQueryEvent e) { AutoCompleteOptions enableOption = new AutoCompleteOptions(); enableOption.MinLength = 0; _autoComplete.AutoComplete(enableOption); _autoComplete.AutoComplete(AutoCompleteMethod.Search, inputField.GetValue()); }); // Bind return to searching _input.Keydown(delegate(jQueryEvent e) { if (e.Which == 13 && !justSelected) // Return pressed - but we want to do a search not move to the next cell { if (inputField.GetValue().Length > 0) { selectButton.Click(); } else { // Set value to null _value = null; return; } } else if (e.Which == 13) { return; } switch (e.Which) { case 13: // Return case 38: // Up - don't navigate - but use the dropdown to select search results case 40: // Down - don't navigate - but use the dropdown to select search results e.PreventDefault(); e.StopPropagation(); break; } justSelected = false; }); }
public string GetValue() { return(input.GetValue()); }
public override void Init(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context) { XrmLookupEditorButton footerButton = (XrmLookupEditorButton)allBindingsAccessor()["footerButton"]; bool showFooter = (bool)allBindingsAccessor()["showFooter"]; jQueryObject container = jQuery.FromElement(element); jQueryObject inputField = container.Find(".sparkle-input-lookup-part"); jQueryObject selectButton = container.Find(".sparkle-input-lookup-button-part"); EntityReference _value = new EntityReference(null, null, null); AutoCompleteOptions options = new AutoCompleteOptions(); options.MinLength = 100000; // Don't enable type down - use search button (or return) options.Delay = 0; options.Position = new Dictionary <string, object>("collision", "fit"); bool justSelected = false; int totalRecordsReturned = 0; Action <AutoCompleteItem, bool> setValue = delegate(AutoCompleteItem item, bool setFocus) { if (_value == null) { _value = new EntityReference(null, null, null); } string value = item.Label; inputField.Value(value); _value.Id = ((Guid)item.Value); _value.Name = item.Label; _value.LogicalName = (string)item.Data; justSelected = true; TrySetObservable(valueAccessor, inputField, _value, setFocus); }; // Set the value when selected options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent) { // Note we assume that the binding has added an array of string items AutoCompleteItem item = (AutoCompleteItem)uiEvent.Item; string data = ((string)item.Data); if (data == "footerlink" || data == null) { footerButton.OnClick(item); e.PreventDefault(); e.StopImmediatePropagation(); Script.Literal("return false;"); } else { setValue(item, true); Script.Literal("return false;"); } }; options.Open = delegate(jQueryEvent e, jQueryObject o) { if (showFooter && totalRecordsReturned > 0) { WidgetObject menu = (WidgetObject)Script.Literal("{0}.autocomplete({1})", inputField, "widget"); XrmLookupEditor.AddFooter(menu, totalRecordsReturned); } }; options.Close = delegate(jQueryEvent e, jQueryObject o) { WidgetObject menu = (WidgetObject)Script.Literal("{0}.autocomplete({1})", inputField, "widget"); jQueryObject footer = menu.Next(); if (footer.Length > 0 || footer.HasClass("sparkle-menu-footer")) { footer.Hide(); } }; // Get the query command Action <string, Action <EntityCollection> > queryCommand = (Action <string, Action <EntityCollection> >)((object)allBindingsAccessor()["queryCommand"]); string nameAttribute = ((string)allBindingsAccessor()["nameAttribute"]); string idAttribute = ((string)allBindingsAccessor()["idAttribute"]); string typeCodeAttribute = ((string)allBindingsAccessor()["typeCodeAttribute"]); string[] columnAttributes = null; // If there multiple names, add them to the columnAttributes string[] columns = nameAttribute.Split(","); if (columns.Length > 1) { columnAttributes = columns; nameAttribute = columnAttributes[0]; } // wire up source to CRM search Action <AutoCompleteRequest, Action <AutoCompleteItem[]> > queryDelegate = delegate(AutoCompleteRequest request, Action <AutoCompleteItem[]> response) { Action <EntityCollection> queryCallBack = delegate(EntityCollection fetchResult) { int recordsFound = fetchResult.Entities.Count; bool noRecordsFound = recordsFound == 0; AutoCompleteItem[] results = new AutoCompleteItem[recordsFound + (footerButton != null ? 1 : 0) + (noRecordsFound ? 1 : 0)]; for (int i = 0; i < recordsFound; i++) { results[i] = new AutoCompleteItem(); results[i].Label = (string)fetchResult.Entities[i].GetAttributeValue(nameAttribute); results[i].Value = fetchResult.Entities[i].GetAttributeValue(idAttribute); results[i].Data = fetchResult.Entities[i].LogicalName; GetExtraColumns(columnAttributes, fetchResult, results, i); string typeCodeName = fetchResult.Entities[i].LogicalName; // Get the type code from the name to find the icon if (!string.IsNullOrEmpty(typeCodeAttribute)) { typeCodeName = fetchResult.Entities[i].GetAttributeValue(typeCodeAttribute).ToString(); } results[i].Image = MetadataCache.GetSmallIconUrl(typeCodeName); } if (fetchResult.TotalRecordCount > fetchResult.Entities.Count) { totalRecordsReturned = fetchResult.TotalRecordCount; } else { totalRecordsReturned = fetchResult.Entities.Count; } int itemsCount = recordsFound; if (noRecordsFound) { AutoCompleteItem noRecordsItem = new AutoCompleteItem(); noRecordsItem.Label = SparkleResourceStrings.NoRecordsFound; results[itemsCount] = noRecordsItem; itemsCount++; } if (footerButton != null) { // Add the add new AutoCompleteItem addNewLink = new AutoCompleteItem(); addNewLink.Label = footerButton.Label; addNewLink.Image = footerButton.Image; addNewLink.ColumnValues = null; addNewLink.Data = "footerlink"; results[itemsCount] = addNewLink; } response(results); // Disable it now so typing doesn't trigger a search AutoCompleteOptions disableOption = new AutoCompleteOptions(); disableOption.MinLength = 100000; inputField.Plugin <AutoCompleteObject>().AutoComplete(disableOption); }; // Call the function with the correct 'this' context Script.Literal("{0}.call({1}.$parent,{2},{3})", queryCommand, context, request.Term, queryCallBack); }; options.Source = queryDelegate; options.Focus = delegate(jQueryEvent e, AutoCompleteFocusEvent uiEvent) { // Prevent the value being updated in the text box we scroll through the results Script.Literal("return false;"); }; inputField = inputField.Plugin <AutoCompleteObject>().AutoComplete(options); // Set render template ((RenderItemDelegate)Script.Literal("{0}.data('ui-autocomplete')", inputField))._renderItem = delegate(object ul, AutoCompleteItem item) { if (item.Data == null) { return((object)jQuery.Select("<li class='ui-state-disabled'>" + item.Label + "</li>").AppendTo((jQueryObject)ul)); } string html = "<a class='sparkle-menu-item'><span class='sparkle-menu-item-img'>"; if (item.Image != null) { html += @"<img src='" + item.Image + "'/>"; } html += @"</span><span class='sparkle-menu-item-label'>" + item.Label + "</span><br>"; if (item.ColumnValues != null && item.ColumnValues.Length > 0) { foreach (string value in item.ColumnValues) { html += "<span class='sparkle-menu-item-moreinfo'>" + value + "</span>"; } } html += "</a>"; return((object)jQuery.Select("<li>").Append(html).AppendTo((jQueryObject)ul)); }; // Add the click binding to show the drop down selectButton.Click(delegate(jQueryEvent e) { AutoCompleteOptions enableOption = new AutoCompleteOptions(); enableOption.MinLength = 0; inputField.Focus(); inputField.Plugin <AutoCompleteObject>().AutoComplete(enableOption); inputField.Plugin <AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search); }); // handle the field changing inputField.Change(delegate(jQueryEvent e) { string inputValue = inputField.GetValue(); if (inputValue != _value.Name) { // The name is different from the name of the lookup reference // search to see if we can auto resolve it TrySetObservable(valueAccessor, inputField, null, false); AutoCompleteRequest lookup = new AutoCompleteRequest(); lookup.Term = inputValue; Action <AutoCompleteItem[]> lookupResults = delegate(AutoCompleteItem[] results) { int selectableItems = 0; // If there is only one, then auto-set if (results != null) { foreach (AutoCompleteItem item in results) { if (isItemSelectable(item)) { selectableItems++; } if (selectableItems > 2) { break; } } } if (selectableItems == 1) { // There is only a single value so set it now setValue(results[0], false); } else { inputField.Value(String.Empty); } }; queryDelegate(lookup, lookupResults); } }); Action disposeCallBack = delegate() { if ((bool)Script.Literal("$({0}).data('ui-autocomplete')!=undefined", inputField)) { Script.Literal("$({0}).autocomplete(\"destroy\")", inputField); } }; //handle disposal (if KO removes by the template binding) Script.Literal("ko.utils.domNodeDisposal.addDisposeCallback({0}, {1})", element, (object)disposeCallBack); Knockout.BindingHandlers["validationCore"].Init(element, valueAccessor, allBindingsAccessor, null, null); // Bind return to searching inputField.Keydown(delegate(jQueryEvent e) { if (e.Which == 13 && !justSelected) // Return pressed - but we want to do a search not move to the next cell { selectButton.Click(); } else if (e.Which == 13) { return; } switch (e.Which) { case 13: // Return case 38: // Up - don't navigate - but use the dropdown to select search results case 40: // Down - don't navigate - but use the dropdown to select search results e.PreventDefault(); e.StopPropagation(); break; } justSelected = false; }); //Script.Literal("return { controlsDescendantBindings: true };"); }
public override void Init(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context) { jQueryObject container = jQuery.FromElement(element); jQueryObject inputField = container.Find(".sparkle-input-lookup-part"); jQueryObject selectButton = container.Find(".sparkle-input-lookup-button-part"); EntityReference _value = new EntityReference(null, null, null); AutoCompleteOptions options = new AutoCompleteOptions(); options.MinLength = 100000; // Don't enable type down - use search button (or return) options.Delay = 0; options.Position = new Dictionary <string, object>("collision", "fit"); bool justSelected = false; // Set the value when selected options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent) { // Note we assume that the binding has added an array of string items AutoCompleteItem item = (AutoCompleteItem)uiEvent.Item; if (_value == null) { _value = new EntityReference(null, null, null); } string value = item.Label; inputField.Value(value); _value.Id = ((Guid)item.Value); _value.Name = item.Label; _value.LogicalName = (string)item.Data; justSelected = true; TrySetObservable(valueAccessor, inputField, _value); Script.Literal("return false;"); }; // Get the query command Action <string, Action <EntityCollection> > queryCommand = (Action <string, Action <EntityCollection> >)((object)allBindingsAccessor()["queryCommand"]); string nameAttribute = ((string)allBindingsAccessor()["nameAttribute"]); string idAttribute = ((string)allBindingsAccessor()["idAttribute"]); string typeCodeAttribute = ((string)allBindingsAccessor()["typeCodeAttribute"]); // wire up source to CRM search Action <AutoCompleteRequest, Action <AutoCompleteItem[]> > queryDelegate = delegate(AutoCompleteRequest request, Action <AutoCompleteItem[]> response) { Action <EntityCollection> queryCallBack = delegate(EntityCollection fetchResult) { AutoCompleteItem[] results = new AutoCompleteItem[fetchResult.Entities.Count]; for (int i = 0; i < fetchResult.Entities.Count; i++) { results[i] = new AutoCompleteItem(); results[i].Label = (string)fetchResult.Entities[i].GetAttributeValue(nameAttribute); results[i].Value = fetchResult.Entities[i].GetAttributeValue(idAttribute); results[i].Data = fetchResult.Entities[i].LogicalName; string typeCodeName = fetchResult.Entities[i].LogicalName; // Get the type code from the name to find the icon if (!string.IsNullOrEmpty(typeCodeAttribute)) { typeCodeName = fetchResult.Entities[i].GetAttributeValue(typeCodeAttribute).ToString(); } results[i].Image = MetadataCache.GetSmallIconUrl(typeCodeName); } response(results); // Disable it now so typing doesn't trigger a search AutoCompleteOptions disableOption = new AutoCompleteOptions(); disableOption.MinLength = 100000; inputField.Plugin <AutoCompleteObject>().AutoComplete(disableOption); }; // Call the function with the correct 'this' context Script.Literal("{0}.call({1}.$parent,{2},{3})", queryCommand, context, request.Term, queryCallBack); }; options.Source = queryDelegate; options.Focus = delegate(jQueryEvent e, AutoCompleteFocusEvent uiEvent) { // Prevent the value being updated in the text box we scroll through the results Script.Literal("return false;"); }; inputField = inputField.Plugin <AutoCompleteObject>().AutoComplete(options); // Set render template ((RenderItemDelegate)Script.Literal("{0}.data('ui-autocomplete')", inputField))._renderItem = delegate(object ul, AutoCompleteItem item) { return((object)jQuery.Select("<li>").Append("<a class='sparkle-menu-item'><span class='sparkle-menu-item-img'><img src='" + item.Image + "'/></span><span class='sparkle-menu-item-label'>" + item.Label + "</span></a>").AppendTo((jQueryObject)ul)); }; // Add the click binding to show the drop down selectButton.Click(delegate(jQueryEvent e) { AutoCompleteOptions enableOption = new AutoCompleteOptions(); enableOption.MinLength = 0; inputField.Focus(); inputField.Plugin <AutoCompleteObject>().AutoComplete(enableOption); inputField.Plugin <AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search); }); // handle the field changing inputField.Change(delegate(jQueryEvent e) { if (inputField.GetValue() != _value.Name) { TrySetObservable(valueAccessor, inputField, null); } }); Action disposeCallBack = delegate() { if ((bool)Script.Literal("$({0}).data('ui-autocomplete')!=undefined", inputField)) { //inputField.Plugin<AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Destroy); Script.Literal("$({0}).autocomplete(\"destroy\")", inputField); } }; //handle disposal (if KO removes by the template binding) Script.Literal("ko.utils.domNodeDisposal.addDisposeCallback({0}, {1})", element, (object)disposeCallBack); Knockout.BindingHandlers["validationCore"].Init(element, valueAccessor, allBindingsAccessor, null, null); // Bind return to searching inputField.Keydown(delegate(jQueryEvent e) { if (e.Which == 13 && !justSelected) // Return pressed - but we want to do a search not move to the next cell { selectButton.Click(); } else if (e.Which == 13) { return; } switch (e.Which) { case 13: // Return case 38: // Up - don't navigate - but use the dropdown to select search results case 40: // Down - don't navigate - but use the dropdown to select search results e.PreventDefault(); e.StopPropagation(); break; } justSelected = false; }); //Script.Literal("return { controlsDescendantBindings: true };"); }
public EmailEditor(jQueryObject input, EmailEditorOptions opt) : base(input, opt) { RegisterValidationMethods(); input.AddClass("emailuser").RemoveClass("flexify"); var spanAt = J("<span/>") .Text("@") .AddClass("emailat") .InsertAfter(input); var domain = J("<input type=\"text\"/>") .AddClass("emaildomain") .AddClass("flexify") .InsertAfter(spanAt); domain.Bind("blur." + this.uniqueName, delegate { var validator = domain.Closest("form").GetDataValue("validator").As <jQueryValidator>(); if (validator != null) { validator.ValidateElement(input[0]); } }); if (!options.Domain.IsEmptyOrNull()) { domain.Value(options.Domain); } if (options.ReadOnlyDomain) { domain.Attribute("readonly", "readonly").AddClass("disabled").Attribute("tabindex", "-1"); } input.Bind("keypress." + this.uniqueName, delegate(jQueryEvent e) { if (e.Which == (int)'@') { e.PreventDefault(); if (!options.ReadOnlyDomain) { domain.Focus(); domain.Select(); } } }); domain.Bind("keypress." + this.uniqueName, delegate(jQueryEvent e) { if (e.Which == (int)'@') { e.PreventDefault(); } }); if (!options.ReadOnlyDomain) { input.Change(e => { this.Value = input.GetValue(); }); } }
public PhoneEditor(jQueryObject input, PhoneEditorOptions opt) : base(input, opt) { var self = this; this.AddValidationRule(this.uniqueName, (e) => { string value = this.Value.TrimToNull(); if (value == null) { return(null); } return(Validate(value)); }); string hint = options.Internal ? "Dahili telefon numarası '456, 8930, 12345' formatlarında" : (options.Mobile ? "Cep telefonu numarası '(533) 342 01 89' formatında" : "Telefon numarası '(216) 432 10 98' formatında"); if (options.Multiple) { hint = hint.Replace("numarası", "numaraları") + " ve birden fazlaysa virgülle ayrılarak "; } hint += " girilmelidir."; input.Attribute("title", hint); input.Bind("change", delegate(jQueryEvent e) { if (!e.HasOriginalEvent()) { return; } FormatValue(); }); input.Bind("blur", delegate(jQueryEvent e) { if (this.element.HasClass("valid")) { FormatValue(); } }); input.Bind("keyup", delegate(jQueryEvent e) { if (options.Internal) { return; } var val = (input.GetValue() ?? ""); if (val.Length > 0 && ((dynamic)input[0]).selectionEnd == val.Length && ((e.Which >= 48 && e.Which <= 57) || (e.Which >= 96 && e.Which <= 105)) && val[val.Length - 1] >= '0' && val[val.Length - 1] <= '9' && !val.StartsWith("+") && val.IndexOf('/') < 0) { if (Validate(val) == null) { FormatValue(); } else { for (var i = 1; i <= 7; i++) { val += "9"; if (Validate(val) == null) { this.Value = val; FormatValue(); val = this.Value; for (var j = 1; j <= i; j++) { val = val.Trim(); val = val.Substr(0, val.Length - 1); } this.Value = val; break; } } } } }); }
public XrmLookupEditor(EditorArguments args) : base(args) { XrmLookupEditor self = this; _args = args; _container = jQuery.FromHtml("<div><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr><td><INPUT type=text class='sparkle-input-inline' /></td><td class='lookup-button-td'><input type=button class='sparkle-lookup-button' /></td></tr></table></div>"); _container.AppendTo(_args.Container); jQueryObject inputField = _container.Find(".sparkle-input-inline"); jQueryObject selectButton = _container.Find(".sparkle-lookup-button"); _input = inputField; _input.Focus().Select(); _autoComplete = inputField.Plugin <AutoCompleteObject>(); AutoCompleteOptions options = new AutoCompleteOptions(); options.Position = new Dictionary <string, object>("collision", "fit"); options.MinLength = 100000; options.Delay = 0; // TODO- set to something that makes sense XrmLookupEditorOptions editorOptions = (XrmLookupEditorOptions)args.Column.Options; bool justSelected = false; options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent) { if (_value == null) { _value = new EntityReference(null, null, null); } // Note we assume that the binding has added an array of string items AutoCompleteItem item = (AutoCompleteItem)uiEvent.Item; EntityReference itemRef = (EntityReference)item.Value; if (itemRef.LogicalName == "footerlink") { XrmLookupEditorButton button = editorOptions.footerButton; button.OnClick(item); } else { string value = item.Label; _input.Value(value); _value.Id = itemRef.Id; _value.Name = itemRef.Name; _value.LogicalName = ((EntityReference)item.Value).LogicalName; justSelected = true; } Script.Literal("return false;"); }; options.Focus = delegate(jQueryEvent e, AutoCompleteFocusEvent uiEvent) { // Prevent the value being updated in the text box as we scroll through the results Script.Literal("return false;"); }; options.Open = delegate(jQueryEvent e, jQueryObject o) { self._searchOpen = true; if (editorOptions.showFooter && totalRecordsReturned > 0) { WidgetObject menu = (WidgetObject)Script.Literal("{0}.autocomplete({1})", _input, "widget"); AddFooter(menu, totalRecordsReturned); } }; options.Close = delegate(jQueryEvent e, jQueryObject o) { self._searchOpen = false; WidgetObject menu = (WidgetObject)Script.Literal("{0}.autocomplete({1})", _input, "widget"); jQueryObject footer = menu.Next(); if (footer.Length > 0 || footer.HasClass("sparkle-menu-footer")) { footer.Hide(); } }; // If there multiple names, add them to the columnAttributes string[] columns = editorOptions.nameAttribute.Split(","); if (columns.Length > 1) { editorOptions.columns = columns; editorOptions.nameAttribute = columns[0]; } // wire up source to CRM search Action <AutoCompleteRequest, Action <AutoCompleteItem[]> > queryDelegate = delegate(AutoCompleteRequest request, Action <AutoCompleteItem[]> response) { // Get the option set values editorOptions.queryCommand(request.Term, delegate(EntityCollection fetchResult) { if (fetchResult.TotalRecordCount > fetchResult.Entities.Count) { totalRecordsReturned = fetchResult.TotalRecordCount; } else { totalRecordsReturned = fetchResult.Entities.Count; } int recordsFound = fetchResult.Entities.Count; bool noRecordsFound = recordsFound == 0; XrmLookupEditorButton button = editorOptions.footerButton; bool footerButton = (button != null); AutoCompleteItem[] results = new AutoCompleteItem[recordsFound + (footerButton ? 1 : 0) + (noRecordsFound ? 1 :0)]; for (int i = 0; i < recordsFound; i++) { results[i] = new AutoCompleteItem(); results[i].Label = (string)fetchResult.Entities[i].GetAttributeValue(editorOptions.nameAttribute); EntityReference id = new EntityReference(null, null, null); id.Name = results[i].Label; id.LogicalName = fetchResult.Entities[i].LogicalName; id.Id = (Guid)fetchResult.Entities[i].GetAttributeValue(editorOptions.idAttribute); results[i].Value = id; XrmLookupBinding.GetExtraColumns(editorOptions.columns, fetchResult, results, i); string typeCodeName = fetchResult.Entities[i].LogicalName; // Get the type code from the name to find the icon if (!string.IsNullOrEmpty(editorOptions.typeCodeAttribute)) { typeCodeName = fetchResult.Entities[i].GetAttributeValue(editorOptions.typeCodeAttribute).ToString(); } if (editorOptions.showImage) { results[i].Image = MetadataCache.GetSmallIconUrl(typeCodeName); } } int itemsCount = recordsFound; if (noRecordsFound) { AutoCompleteItem noRecordsItem = new AutoCompleteItem(); noRecordsItem.Label = SparkleResourceStrings.NoRecordsFound; results[itemsCount] = noRecordsItem; itemsCount++; } if (footerButton) { // Add the add new AutoCompleteItem addNewLink = new AutoCompleteItem(); addNewLink.Label = button.Label; addNewLink.Image = button.Image; addNewLink.ColumnValues = null; addNewLink.Value = new Entity("footerlink"); results[itemsCount] = addNewLink; } response(results); // Disable it now so typing doesn't trigger a search AutoCompleteOptions disableOption = new AutoCompleteOptions(); disableOption.MinLength = 100000; _autoComplete.AutoComplete(disableOption); }); }; options.Source = queryDelegate; inputField = _autoComplete.AutoComplete(options); RenderItemDelegate autoCompleteDelegates = ((RenderItemDelegate)Script.Literal("{0}.data('ui-autocomplete')", inputField)); autoCompleteDelegates._renderItem = delegate(object ul, AutoCompleteItem item) { if (item.Value == item.Label) { return((object)jQuery.Select("<li class='ui-state-disabled'>" + item.Label + "</li>").AppendTo((jQueryObject)ul)); } string itemHtml = "<a class='sparkle-menu-item'>"; // Allow for no image by passing false to 'ShowImage' on the XrmLookupEditorOptions options if (item.Image != null) { itemHtml += "<span class='sparkle-menu-item-img'><img src='" + item.Image + "'/></span>"; } itemHtml += "<span class='sparkle-menu-item-label'>" + item.Label + "</span><br/>"; if (item.ColumnValues != null && item.ColumnValues.Length > 0) { foreach (string value in item.ColumnValues) { itemHtml += "<span class='sparkle-menu-item-moreinfo'>" + value + "</span>"; } } itemHtml += "</a>"; return((object)jQuery.Select("<li>").Append(itemHtml).AppendTo((jQueryObject)ul)); }; // Add the click binding to show the drop down selectButton.Click(delegate(jQueryEvent e) { AutoCompleteOptions enableOption = new AutoCompleteOptions(); enableOption.MinLength = 0; _autoComplete.AutoComplete(enableOption); _autoComplete.AutoComplete(AutoCompleteMethod.Search, inputField.GetValue()); }); // Bind return to searching _input.Keydown(delegate(jQueryEvent e) { if (e.Which == 13 && !justSelected) // Return pressed - but we want to do a search not move to the next cell { if (inputField.GetValue().Length > 0) { selectButton.Click(); } else { // Set value to null _value = null; return; } } else if (e.Which == 13) { return; } if (self._searchOpen) { switch (e.Which) { case 9: case 13: // Return case 38: // Up - don't navigate - but use the dropdown to select search results case 40: // Down - don't navigate - but use the dropdown to select search results e.PreventDefault(); e.StopPropagation(); break; } } else { switch (e.Which) { case 13: // Return e.PreventDefault(); e.StopPropagation(); break; } } justSelected = false; }); }