public static void init() { ContactsEditorViewModel vm = new ContactsEditorViewModel(); OrganizationServiceProxy.GetUserSettings(); // Data Bind Grid List <Column> columns = GridDataViewBinder.ParseLayout(",entityState,20,First Name,firstname,200,Last Name,lastname,200,Birth Date,birthdate,200,Account Role Code,accountrolecode,200,Number of Children,numberofchildren,100,Currency,transactioncurrencyid,200,Credit Limit,creditlimit,100,Gender,gendercode,100,Owner,ownerid,100"); // Set Column formatters and editors columns[0].Formatter = delegate(int row, int cell, object value, Column columnDef, object dataContext) { EntityStates state = (EntityStates)value; return(((state == EntityStates.Changed) || (state == EntityStates.Created)) ? "<span class='grid-edit-indicator'></span>" : ""); }; // First Name Column XrmTextEditor.BindColumn(columns[1]); // Last Name Column XrmTextEditor.BindColumn(columns[2]); // Birth Date Column XrmDateEditor.BindColumn(columns[3], false); // Account Code Column XrmOptionSetEditor.BindColumn(columns[4], "contact", columns[4].Field, true); // Number of Children Column XrmNumberEditor.BindColumn(columns[5], 0, 100, 0); // Currency Column XrmLookupEditor.BindColumn(columns[6], vm.TransactionCurrencySearchCommand, "transactioncurrencyid", "currencyname", ""); // Credit Limit Column XrmMoneyEditor.BindColumn(columns[7], -10000, 10000); // Another optionset XrmOptionSetEditor.BindColumn(columns[8], "contact", columns[8].Field, true); // OWner Column XrmLookupEditor.BindColumn(columns[9], vm.OwnerSearchCommand, "id", "name", ""); // Create Grid GridDataViewBinder contactGridDataBinder = new GridDataViewBinder(); Grid contactsGrid = contactGridDataBinder.DataBindXrmGrid(vm.Contacts, columns, "container", "pager", true, false); //contactGridDataBinder.BindClickHandler(contactsGrid); // Data Bind ViewBase.RegisterViewModel(vm); Window.SetTimeout(delegate() { vm.Init(); }, 0); }
private static void InitLocalisedContent() { Dictionary <string, string> entityTypes; string id; string logicalName; #if DEBUG id = "C489707F-B5E2-E411-80D5-080027846324"; logicalName = "account"; entityTypes = new Dictionary <string, string>(); entityTypes["account"] = "name"; entityTypes["contact"] = "fullname"; entityTypes["opportunity"] = "name"; #else entityTypes = PageEx.GetWebResourceData(); // The allowed lookup types for the connections - e.g. account, contact, opportunity. This must be passed as a data parameter to the webresource 'account=name&contact=fullname&opportunity=name id = ParentPage.Data.Entity.GetId(); logicalName = ParentPage.Data.Entity.GetEntityName(); #endif EntityReference parent = new EntityReference(new Guid(id), logicalName, null); vm = new ConnectionsViewModel(parent, entityTypes); // Bind Connections grid GridDataViewBinder contactGridDataBinder = new GridDataViewBinder(); List <Column> columns = GridDataViewBinder.ParseLayout(String.Format("{0},record1id,250,{1},record1roleid,250", ResourceStrings.ConnectTo, ResourceStrings.Role)); // Role2Id Column XrmLookupEditor.BindColumn(columns[1], vm.RoleSearchCommand, "connectionroleid", "name", ""); connectionsGrid = contactGridDataBinder.DataBindXrmGrid(vm.Connections, columns, "container", "pager", true, false); connectionsGrid.OnActiveCellChanged.Subscribe(delegate(EventData e, object data) { OnCellChangedEventData eventData = (OnCellChangedEventData)data; vm.SelectedConnection.SetValue((Connection)connectionsGrid.GetDataItem(eventData.Row)); }); // Let's not use a hover button because it get's n the way of the editable grid! //RowHoverPlugin rowButtons = new RowHoverPlugin("gridButtons"); //connectionsGrid.RegisterPlugin(rowButtons); ViewBase.RegisterViewModel(vm); OverrideMetadata(); jQuery.Window.Resize(OnResize); jQuery.OnDocumentReady(delegate() { OnResize(null); vm.Search(); }); }
public static void init() { QuoteLineItemEditorViewModel vm = new QuoteLineItemEditorViewModel(); List <Column> columns = new List <Column>(); GridDataViewBinder.AddEditIndicatorColumn(columns); XrmNumberEditor.BindReadOnlyColumn( GridDataViewBinder.AddColumn(columns, "#", 40, "lineitemnumber"), 0); XrmLookupEditor.BindColumn( GridDataViewBinder.AddColumn(columns, "Existing Product", 200, "productid"), vm.ProductSearchCommand, "productid", "name", ""); XrmLookupEditor.BindColumn( GridDataViewBinder.AddColumn(columns, "Units", 100, "uomid"), vm.UoMSearchCommand, "uomid", "name", ""); XrmTextEditor.BindColumn( GridDataViewBinder.AddColumn(columns, "Write-In Product", 200, "productdescription")); XrmMoneyEditor.BindColumn( GridDataViewBinder.AddColumn(columns, "Price Per Unit", 200, "priceperunit"), 0, 1000); XrmNumberEditor.BindColumn( GridDataViewBinder.AddColumn(columns, "Quantity", 200, "quantity"), 0, 1000, 2); XrmMoneyEditor.BindReadOnlyColumn( GridDataViewBinder.AddColumn(columns, "Extended Amount", 100, "extendedamount")); GridDataViewBinder contactGridDataBinder = new GridDataViewBinder(); Grid contactsGrid = contactGridDataBinder.DataBindXrmGrid(vm.Lines, columns, "quoteproductGrid", "quoteproductPager", true, true); contactGridDataBinder.BindCommitEdit(vm); ViewBase.RegisterViewModel(vm); Window.SetTimeout(delegate() { vm.Lines.Refresh(); }, 0); }
public static void Init() { PageEx.MajorVersion = 2013; jQuery.OnDocumentReady(delegate() { ValidationApi.RegisterExtenders(); // Init settings OrganizationServiceProxy.GetUserSettings(); SimpleEditableGridViewModel vm = new SimpleEditableGridViewModel(); // Create Grid GridDataViewBinder dataViewBinder = new GridDataViewBinder(); dataViewBinder.AddCheckBoxSelectColumn = true; dataViewBinder.SelectActiveRow = true; dataViewBinder.MultiSelect = false; List <Column> columns = new List <Column>(); EditorFactory textEditor = (EditorFactory)Script.Literal("Slick.Editors.Text"); XrmTextEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Title", 150, "title")); XrmTextEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Author", 150, "author")); XrmDateEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Published", 150, "publishdate"), true); XrmMoneyEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Price", 150, "price"), 0, 100); XrmNumberEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Copies", 150, "numberofcopies"), 0, 1000, 0); XrmLookupEditorOptions languageLookupOptions = (XrmLookupEditorOptions)XrmLookupEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Language", 150, "language"), vm.GetLanguages, "id", "name", null).Options; languageLookupOptions.showImage = false; OptionSetBindingOptions formatBindingOptions = new OptionSetBindingOptions(); formatBindingOptions.allowEmpty = true; formatBindingOptions.GetOptionSetsDelegate = vm.GetFormats; XrmOptionSetEditor.BindColumnWithOptions(GridDataViewBinder.AddColumn(columns, "Format", 150, "format"), formatBindingOptions); XrmDurationEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Audio Length", 150, "audiolength")); XrmTimeEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Start Time", 150, "starttime")); Grid grid = dataViewBinder.DataBindXrmGrid(vm.Books, columns, "booksGridContainer", null, true, true); ViewBase.RegisterViewModel(vm); Window.SetTimeout(delegate() { vm.LoadBooks(); grid.ResizeCanvas(); }, 0); }); }
public static void init() { ContactsEditorViewModel vm = new ContactsEditorViewModel(); // Data Bind Grid List <Column> columns = GridDataViewBinder.ParseLayout("entityState,,20,firstname,First Name,200,lastname,Last Name,200,birthdate,Birth Date,200,accountrolecode,Account Role Code,200,numberofchildren,Number of Children,100,transactioncurrencyid,Currency,200,creditlimit,Credit Limit,100"); // Set Column formatters and editors columns[0].Formatter = delegate(int row, int cell, object value, Column columnDef, object dataContext) { EntityStates state = (EntityStates)value; return(((state == EntityStates.Changed) || (state == EntityStates.Created)) ? "<span class='grid-edit-indicator'></span>" : ""); }; // First Name Column XrmTextEditor.BindColumn(columns[1]); // Last Name Column XrmTextEditor.BindColumn(columns[2]); // Birth Date Column XrmDateEditor.BindColumn(columns[3], false); // Account Code Column XrmOptionSetEditor.BindColumn(columns[4], "contact", columns[4].Field, true); // Number of Children Column XrmNumberEditor.BindColumn(columns[5], 0, 100, 0); // Currency Column XrmLookupEditor.BindColumn(columns[6], vm.TransactionCurrencySearchCommand, "transactioncurrencyid", "currencyname", ""); // Credit Limit Column XrmMoneyEditor.BindColumn(columns[7], -10000, 10000); // Create Grid GridDataViewBinder contactGridDataBinder = new GridDataViewBinder(); Grid contactsGrid = contactGridDataBinder.DataBindXrmGrid(vm.Contacts, columns, "container", "pager", true, false); // Data Bind ViewBase.RegisterViewModel(vm); }
private static void InitLocalisedContent() { Dictionary <string, string> parameters; string id; string logicalName; int pageSize = 10; string defaultView = null; #if DEBUG id = "C489707F-B5E2-E411-80D5-080027846324"; logicalName = "account"; parameters = new Dictionary <string, string>(); #else parameters = PageEx.GetWebResourceData(); // The allowed lookup types for the connections - e.g. account, contact, opportunity. This must be passed as a data parameter to the webresource 'account=name&contact=fullname&opportunity=name id = ParentPage.Data.Entity.GetId(); logicalName = ParentPage.Data.Entity.GetEntityName(); ParentPage.Data.Entity.AddOnSave(CheckForSaved); #endif EntityReference parent = new EntityReference(new Guid(id), logicalName, null); string entities = "account,contact,opportunity,systemuser"; foreach (string key in parameters.Keys) { switch (key.ToLowerCase()) { case "entities": entities = parameters[key]; break; case "pageSize": pageSize = int.Parse(parameters[key]); break; case "view": defaultView = parameters[key]; break; } } // Get the view QueryParser queryParser = new QueryParser(new string[] { "connection" }); queryParser.GetView("connection", defaultView); queryParser.QueryMetadata(); EntityQuery connectionViews = queryParser.EntityLookup["connection"]; string viewName = connectionViews.Views.Keys[0]; FetchQuerySettings view = connectionViews.Views[viewName]; vm = new ConnectionsViewModel(parent, entities.Split(","), pageSize, view); // Bind Connections grid GridDataViewBinder connectionsGridDataBinder = new GridDataViewBinder(); List <Column> columns = view.Columns; // Role2Id Column - provided it is in the view! foreach (Column col in columns) { switch (col.Field) { case "record2roleid": XrmLookupEditor.BindColumn(col, vm.RoleSearchCommand, "connectionroleid", "name,category", ""); break; case "description": XrmTextEditor.BindColumn(col); break; case "effectivestart": case "effectiveend": XrmDateEditor.BindColumn(col, true); break; } } connectionsGrid = connectionsGridDataBinder.DataBindXrmGrid(vm.Connections, columns, "container", "pager", true, false); connectionsGrid.OnActiveCellChanged.Subscribe(delegate(EventData e, object data) { OnCellChangedEventData eventData = (OnCellChangedEventData)data; vm.SelectedConnection.SetValue((Connection)connectionsGrid.GetDataItem(eventData.Row)); }); connectionsGridDataBinder.BindClickHandler(connectionsGrid); // Let's not use a hover button because it get's in the way of the editable grid! //RowHoverPlugin rowButtons = new RowHoverPlugin("gridButtons"); //connectionsGrid.RegisterPlugin(rowButtons); ViewBase.RegisterViewModel(vm); OverrideMetadata(); jQuery.Window.Resize(OnResize); jQuery.OnDocumentReady(delegate() { OnResize(null); vm.Search(); }); }
public static void SetUpGrids(TimeSheetViewModel vm) { // Create Timesheet Grid DataViewBase daysDataView = vm.Days; List <Column> columns = new List <Column>(); GridDataViewBinder.BindRowIcon(GridDataViewBinder.AddColumn(columns, "", 50, "icon"), "activity"); XrmLookupEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Account", 300, "account"), vm.AccountSeachCommand, "accountid", "name", null); XrmLookupEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Regarding", 300, "regardingObjectId"), vm.RegardingObjectSearchCommand, "id", "displayName", null); XrmLookupEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Activity", 300, "activity"), vm.ActivitySearchCommand, "activityid", "subject", "activitytypecode"); string[] daysOfWeek = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; int firstDayOfWeek = OrganizationServiceProxy.OrganizationSettings.WeekStartDayCode.Value.Value; GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek], 50, "day0"); GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek + 1], 50, "day1"); GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek + 2], 50, "day2"); GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek + 3], 50, "day3"); GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek + 4], 50, "day4"); GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek + 5], 50, "day5"); GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek + 6], 50, "day6"); GridDataViewBinder daysDataBinder = new GridDataViewBinder(); daysDataBinder.SelectActiveRow = true; daysDataBinder.AddCheckBoxSelectColumn = false; daysGrid = daysDataBinder.DataBindXrmGrid(daysDataView, columns, "timesheetGridContainer", null, true, true); // Set the totals row meta data daysDataView.OnGetItemMetaData += delegate(object item) { ItemMetaData metaData = new ItemMetaData(); DayEntry day = (DayEntry)item; if (day != null && day.isTotalRow) { metaData.Editor = delegate(EditorArguments args) { return(null); }; metaData.Columns = new Dictionary <object, Column>(); metaData.Columns["Account"] = new Column("editor", null); metaData.Columns["Regarding"] = new Column("editor", null); metaData.Columns["Activity"] = new Column("editor", null); metaData.Formatter = delegate(int row, int cell, object value, Column columnDef, object dataContext) { switch (columnDef.Field) { case "account": case "regardingObjectId": return(""); case "activity": return("Total"); default: return(XrmDurationEditor.Formatter(row, cell, value, columnDef, dataContext)); } }; metaData.CssClasses = "days_total_row"; } else { metaData.Formatter = delegate(int row, int cell, object value, Column columnDef, object dataContext) { switch (columnDef.Field) { case "account": case "regardingObjectId": case "activity": return(XrmLookupEditor.Formatter(row, cell, value, columnDef, dataContext)); default: return(XrmDurationEditor.Formatter(row, cell, value, columnDef, dataContext)); } }; } return(metaData); }; daysDataBinder.DataBindSelectionModel(daysGrid, daysDataView); // --------------------------------------- // Sessions Grid // --------------------------------------- DataViewBase sessionsDataView = vm.SessionDataView; List <Column> sessionGridCols = new List <Column>(); GridDataViewBinder.AddEditIndicatorColumn(sessionGridCols); XrmTextEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Activity", 300, "activitypointer_subject")).Editor = null; XrmDateEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Date", 100, "dev1_starttime"), true); XrmTimeEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Start", 100, "dev1_starttime")).Validator = delegate(object value, object item) { dev1_session session = (dev1_session)item; DateTime newStartTime = (DateTime)value; ValidationResult result = new ValidationResult(); if (session.dev1_EndTime != null) { result.Valid = true; string valueText = (string)value; // Check if the end time is before the start time bool isValid = DateTimeEx.GetTimeDuration(newStartTime) < DateTimeEx.GetTimeDuration(session.dev1_EndTime); result.Valid = isValid; result.Message = "The start time must be before the end time"; } else { result.Valid = true; } return(result); }; XrmTimeEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "End", 100, "dev1_endtime")).Validator = delegate(object value, object item) { dev1_session session = (dev1_session)item; DateTime newEndTime = (DateTime)value; ValidationResult result = new ValidationResult(); if (session.dev1_StartTime != null) { result.Valid = true; string valueText = (string)value; // Check if the end time is before the start time bool isValid = DateTimeEx.GetTimeDuration(session.dev1_StartTime) < DateTimeEx.GetTimeDuration(newEndTime); result.Valid = isValid; result.Message = "The end time must be after the start time"; } else { result.Valid = true; } return(result); }; XrmDurationEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Duration", 70, "dev1_duration")); XrmTextEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Description", 300, "dev1_description")); GridDataViewBinder sessionsDataBinder = new GridDataViewBinder(); sessionsDataBinder.SelectActiveRow = false; sessionsDataBinder.AddCheckBoxSelectColumn = true; sessionsGrid = sessionsDataBinder.DataBindXrmGrid(sessionsDataView, sessionGridCols, "sessionsGridContainer", null, true, true); sessionsGrid.OnBeforeEditCell.Subscribe(delegate(EventData e, object args) { // Stop the row from being edited if locked Entity item = (Entity)((EditEventData)args).item; bool result = sessionsDataView.OnBeforeEdit(item); Script.Literal("return {0}", result); }); daysGrid.OnActiveCellChanged.Subscribe(delegate(EventData e, object args) { CellSelection activeCell = daysGrid.GetActiveCell(); if (activeCell != null) { if (activeCell.Cell < StartDaysColumnIndex) { // Whole activity is selected vm.Days.SelectedDay = null; } else { vm.Days.SelectedDay = activeCell.Cell - (StartDaysColumnIndex - 1); } } }); }
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 static void SetUpGrids(TimeSheetViewModel vm) { GridOptions daysGridOpts = new GridOptions(); daysGridOpts.EnableCellNavigation = true; daysGridOpts.EnableColumnReorder = false; daysGridOpts.AutoEdit = false; daysGridOpts.Editable = true; daysGridOpts.RowHeight = 20; daysGridOpts.HeaderRowHeight = 25; daysGridOpts.ForceFitColumns = false; daysGridOpts.EnableAddRow = true; // Create Timesheet Grid DataViewBase daysDataView = vm.Days; List <Column> columns = new List <Column>(); GridDataViewBinder.BindRowIcon(GridDataViewBinder.AddColumn(columns, "", 50, "icon"), "activity"); XrmLookupEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Activity", 300, "activity"), vm.ActivitySearchCommand, "activityid", "subject", "activitytypecode"); GridDataViewBinder.AddColumn(columns, "Mon", 50, "day0"); GridDataViewBinder.AddColumn(columns, "Tue", 50, "day1"); GridDataViewBinder.AddColumn(columns, "Wed", 50, "day2"); GridDataViewBinder.AddColumn(columns, "Thu", 50, "day3"); GridDataViewBinder.AddColumn(columns, "Fri", 50, "day4"); GridDataViewBinder.AddColumn(columns, "Sat", 50, "day5"); GridDataViewBinder.AddColumn(columns, "Sun", 50, "day6"); daysGrid = new Grid("#timesheetGridContainer", daysDataView, columns, daysGridOpts); GridDataViewBinder daysDataBinder = new GridDataViewBinder(); daysDataBinder.DataBindEvents(daysGrid, daysDataView, "timesheetGridContainer"); // Set the totals row meta data daysDataView.OnGetItemMetaData += delegate(object item) { DayEntry day = (DayEntry)item; if (day != null && day.isTotalRow) { ItemMetaData metaData = new ItemMetaData(); metaData.Editor = null; metaData.Formatter = delegate(int row, int cell, object value, Column columnDef, object dataContext) { if (columnDef.Field == "activity") { return("Total"); } else { return(Formatters.DefaultFormatter(row, cell, value, columnDef, dataContext)); } }; metaData.CssClasses = "days_total_row"; return(metaData); } else { return(null); } }; daysDataBinder.DataBindSelectionModel(daysGrid, daysDataView); // --------------------------------------- // Sessions Grid // --------------------------------------- DataViewBase sessionsDataView = vm.SessionDataView; List <Column> sessionGridCols = new List <Column>(); GridDataViewBinder.AddEditIndicatorColumn(sessionGridCols); XrmTextEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Description", 200, "dev1_description")); XrmDateEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Date", 200, "dev1_starttime"), true); XrmTimeEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Start", 100, "dev1_starttime")).Validator = delegate(object value, object item) { dev1_session session = (dev1_session)item; DateTime newStartTime = (DateTime)value; ValidationResult result = new ValidationResult(); if (session.dev1_EndTime != null) { result.Valid = true; string valueText = (string)value; // Check if the end time is before the start time bool isValid = DateTimeEx.GetTimeDuration(newStartTime) < DateTimeEx.GetTimeDuration(session.dev1_EndTime); result.Valid = isValid; result.Message = "The start time must be before the end time"; } else { result.Valid = true; } return(result); }; XrmTimeEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "End", 100, "dev1_endtime")).Validator = delegate(object value, object item) { dev1_session session = (dev1_session)item; DateTime newEndTime = (DateTime)value; ValidationResult result = new ValidationResult(); if (session.dev1_StartTime != null) { result.Valid = true; string valueText = (string)value; // Check if the end time is before the start time bool isValid = DateTimeEx.GetTimeDuration(session.dev1_StartTime) < DateTimeEx.GetTimeDuration(newEndTime); result.Valid = isValid; result.Message = "The end time must be after the start time"; } else { result.Valid = true; } return(result); }; XrmDurationEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Duration", 200, "dev1_duration")); GridDataViewBinder sessionsDataBinder = new GridDataViewBinder(); sessionsGrid = sessionsDataBinder.DataBindXrmGrid(sessionsDataView, sessionGridCols, "sessionsGridContainer", null, true, true); sessionsDataBinder.DataBindSelectionModel(sessionsGrid, sessionsDataView); daysGrid.OnActiveCellChanged.Subscribe(delegate(EventData e, object args) { CellSelection activeCell = daysGrid.GetActiveCell(); if (activeCell != null) { if (activeCell.Cell < 2) { // Whole activity is selected vm.Days.SelectedDay = null; } else { vm.Days.SelectedDay = activeCell.Cell - 1; } } }); }