Displaying a separator view in CollectionView - marionette

I've got a Collection that is sorted by model's datetime property. I need to display a 'separator view' whenever the day changes. I was thinking about using a CollectionView to display the data. Am I on the right track?
The end result would look something like this:
1st of September (separator view)
-----------------------------
Model1
Model2
2nd of September (separator view)
-----------------------------
Model3

The solution was to extend the CollectionView's appendHtml method.
appendHtml: (collectionView, itemView, index) ->
if #_isDayChanged index
itemView.separator = true
itemView.render()
super

I use a list of CompositeViews to divide collection items in groups by month. You can easily adapt it to group by days.
let ItemView = Marionette.ItemView.extend({
...
});
let ListView = Marionette.CompositeView.extend({
childView: ItemView,
template: template,
childViewContainer: '.items',
filter(child) {
return child.get('month') === this.model.get('month');
}
});
let MonthGroupedListView = Marionette.CollectionView.extend({
childView: ListView,
childViewOptions(item, index) {
return {
model: item,
collection: this.getOption('collection')
};
},
initialize() {
// Passed collection remains in this.options.collection
// this.collection will contain distinct months
this.collection = new Backbone.Collection();
this.reset();
this.listenTo(this.options.collection, 'sync update', this.reset);
},
reset() {
// Find distnct months and put them into the collection
let months = _.uniq(this.options.collection.map((model) => model.get('month')));
this.collection.reset(_.map(months, (month) => ({month})));
}
});
From the data below the result should be three groups of ListView:
let data = [
{ id: 1, month: '2015-01', title: "January item 1" },
{ id: 2, month: '2015-01', title: "January item 2" },
{ id: 3, month: '2015-02', title: "February item 1" },
{ id: 4, month: '2015-05', title: "May item 1" },
{ id: 5, month: '2015-05', title: "May item 2" },
{ id: 6, month: '2015-05', title: "May item 3" }
];
let view = new MonthGroupedListView({
collection: new Backbone.Collection(data)
});
The template for ListView looks like this:
<div class="month-header">
{{month}}
</div>
<ul class="items">
{{-- Here ItemView elements will be rendered --}}
</ul>

Related

How to filter/sort OpenUI5 Grid by column, which is nested in the json?

I'm now testing the capabilities of this grid and I'm having a look at this example at the moment.
Last week, I tried some basic loading of data, returned from the controller of the MVC app that I'm working on. It returns json, which I then give to the grid to be displayed.
The data, that I want to show, is stored in multiple tables. For now, I load data from only two of them for simplicity, because I'm only testing the capabilities of the grid - will it suit our needs.
The data, which arrives at the grid (in js), looks something like this:
{
Cars: [
{
car_Number: '123',
car_Color: 'red',
car_Owner: Owner: {
owner_ID: '234',
owner_Name: 'John'
},
car_DateBought: '/Date(1450648800000)/'
},
{
car_Number: '456',
car_Color: 'yellow',
car_Owner: Owner: {
owner_ID: '345',
owner_Name: 'Peter'
},
car_DateBought: '/Date(1450648800000)/'
},
{
car_Number: '789',
car_Color: 'green',
car_Owner: Owner: {
owner_ID: '567',
owner_Name: 'Michael'
},
car_DateBought: '/Date(1450648800000)/'
}
]
}
Here is some sample code of what I have done so far:
$.ajax({
type: 'post',
url: BASE_HREF + 'OpenUI5/GetAllCars',
success: function (result) {
var dataForGrid = result['rows'];
debugger;
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(dataForGrid);
var oTable = new sap.ui.table.Table({
selectionMode: sap.ui.table.SelectionMode.Multi,
selectionBehavior: sap.ui.table.SelectionBehavior.Row,
visibleRowCountMode: sap.ui.table.VisibleRowCountMode.Auto,
minAutoRowCount: 10,
//visibleRowCount: 10,
showNoData: false
});
// define the Table columns and the binding values
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "ID of car"
}),
template: new sap.ui.commons.TextView({ text: "{car_Number}" }),
sortProperty: "car_Number", // https://sapui5.netweaver.ondemand.com/sdk/test-resources/sap/ui/table/demokit/Table.html#__2
filterProperty: "car_Number"
}));
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({ text: "Color of car" }),
template: new sap.ui.commons.TextView({ text: "{car_Color}" }),
sortProperty: "car_Color",
filterProperty: "car_Color"
}));
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({ text: "Car Owner ID" }),
template: new sap.ui.commons.TextView({
// does not work like this -> text: "{Owner.owner_ID}"
text: {
path: 'Owner',
formatter: function (owner) {
return owner !== null ? owner['owner_ID'] : '';
}
}
}),
sortProperty: "Owner.owner_ID", // these two don't work
filterProperty: "Owner.owner_ID"
}));
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({ text: "Car Owner Name" }),
template: new sap.ui.commons.TextView({
// does not work like this -> text: "{Owner.owner_Name}"
text: {
path: 'Owner',
formatter: function (owner) {
return owner !== null ? owner['Name'] : '';
}
}
}),
sortProperty: "Owner.owner_Name", // these two don't work
filterProperty: "Owner.owner_Name"
}));
var dateType = new sap.ui.model.type.Date({ // http://stackoverflow.com/questions/22765286/how-to-use-a-table-column-filter-with-formatted-columns
pattern: "dd-MM-yyyy"
});
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({ text: "Date bought" }),
template: new sap.ui.commons.TextView({
text: {
path: 'car_DateBought',
formatter: dateFormatterBG
}
}),
sortProperty: "car_DateBought",
filterProperty: "car_DateBought",
filterType: dateType
}));
oTable.setModel(oModel);
oTable.bindRows("/");
oTable.placeAt("testTable", "only");
},
error: function (xhr, status, errorThrown) {
console.log("XHR:");
console.log(xhr);
console.log("Status:");
console.log(status);
console.log("ErrorThrown:");
console.log(errorThrown);
}
});
My problems:
I cannot sort or filter the list of cars by owner_ID or owner_Name. How should I do the filtering and sorting? Should it be done with the help of a formatter function in some way, or...?
I can sort by car_DateBought, but I cannot filter the cars by this field. First, I tried setting filterType: dateType, then I tried setting it to filterType: dateFormatterBG(it turns out, that dateType does exactly the same thing as my own dateFormatterBG does, btw).
function dateFormatterBG(cellvalue, options, rowObject) {
var formatedDate = '';
if ((cellvalue != undefined)) {
var date = new Date(parseInt(cellvalue.substr(6)));
var month = '' + (date.getMonth() + 1);
var day = '' + date.getDate();
var year = date.getFullYear();
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
formatedDate = [day, month, year].join('-');
}
return formatedDate;
}
Anyway, as I said, I tried both, but it doesn't work. When I click on the header of a column like in the example in the first link, I don't get any sort of a datepicker. How can I tell OpenUI5, that this column needs to be filtered by date and it should provide the user with a datepicker, when he/she clicks on the 'Filter' input field at the bottom of the dropdown menu? When I try to write the date in the filter field like '07-11-2016' (the way it is formatted), I get an empty table/grid. If I try to enter the huge number from field car_DateBought in the json object, all available rows in the table stay the same and when I reclick on the header, the filter field at the bottom of the dropdown menu appears with error-state.
Thank you in advance for your help and pieces of advice!
Edit:
This is just sample, dummy data. I try to load the real data and I see, that in the table I've got a couple of rows with date, which is today (07-11-2016, or 11/7/2016 if you prefer). That's why getting an empty table after trying to filter means it's not working correctly.
Sorting: in a sample I am looking at the following appears in the controller:
onInit : function () {
this._IDSorter = new sap.ui.model.Sorter("my_id", false);
},
....
Then in the view there is a button defined in the header column as
<Column>
<Label text="Project"/>
<Button icon="sap-icon://sort" press="onSortID" />
</Column>
And back in the controller there is a further function:
onSortID: function(){
this._IDSorter.bDescending = !this._IDSorter.bDescending;
this.byId("table").getBinding("items").sort(this._IDSorter);
},
I read this collectively as defining a sorter in the onInit(), then toggle/reversing it in the click event of the sort button in the column header via the onSortId() function. The OpenUI5 API doc re sorters indicates there are more parameters in the sorter constructor for initial sort direction and sorting function.
Following this pattern, for your needs to sort on the owner_ID or owner_Name, I assume you could set up a sorter as
this._OwnerIDSorter = new sap.ui.model.Sorter("car_Owner/owner_ID", false);
this._OwnerNameSorter = new sap.ui.model.Sorter("car_Owner/owner_Name", false);

Filter Kendo Dropdownlist values within a kendo grid row based on value from another row

I have Kendo Grid, inside which I have dropdown input [editable]. Now I want to filter the values in dropdown based on value present in row next to it. For ex:
_________________________________________
Column 1 | Column 2 (this is a dropdown)
_________________________________________
A | Show only values relevant to A
__________________________________________
B | Show values relevant to B
_____________________________________________
C | Show values relevant to C
_________________________________________
you can do the following
On editing the row get the name from the first column
filter the second column based on the first column value
In the given sample below, I edited an existing sample provided by the Kendo UI for cascading dropdowns, so I wrote extra codes to get the Id of the first column, so in your case you can exclude the additional steps
The HTML needed
<div id="grid"></div>
The scripts needed
<script>
// array of all brands
var brands = [
{ brandId: 1, name: "Ford" },
{ brandId: 2, name: "BMW" }
];
// array of all models
var models = [
{ modelId: 1, name: "Explorer", brandId: 1},
{ modelId: 2, name: "Focus", brandId: 1},
{ modelId: 3, name: "X3", brandId: 2},
{ modelId: 4, name: "X5", brandId: 2}
];
$("#grid").kendoGrid({
dataSource: {
data: [
{ id: 1, brandId: 1, modelId: 2 }, // initial data item (Ford, Focus)
{ id: 2, brandId: 2, modelId: 3 } // initial data item (BMW, X3)
],
schema: {
model: {
id: "id",
fields: {
id: { editable: false }, // the id field is not editable
brandId: {editable: false}
}
}
}
},
editable: "inline", // use inline mode so both dropdownlists are visible (required for cascading)
columns: [
{ field: "id" },
{
// the brandId column
title: "Brand",
field: "brandId", // bound to the brandId field
template: "#= brandName(brandId) #", // the template shows the name corresponding to the brandId field
},
{
//The modelId column
title: "Model",
field: "modelId", // bound to the modelId field
template: "#= modelName(modelId) #", //the template shows the name corresponding to the modelId field
editor: function(container) { // use a dropdownlist as an editor
var input = $('<input id="modelId" name="modelId">');
input.appendTo(container);
input.kendoDropDownList({
dataTextField: "name",
dataValueField: "modelId",
//cascadeFrom: "brandId", // cascade from the brands dropdownlist
dataSource: filterModels() // bind it to the models array
}).appendTo(container);
}
},
{ command: "edit" }
]
});
function brandName(brandId) {
for (var i = 0; i < brands.length; i++) {
if (brands[i].brandId == brandId) {
return brands[i].name;
}
}
}
function brandId(brandName) {
for (var i = 0; i < brands.length; i++) {
if (brands[i].name == brandName) {
return brands[i].brandId;
}
}
}
function modelName(modelId) {
for (var i = 0; i < models.length; i++) {
if (models[i].modelId == modelId) {
return models[i].name;
}
}
}
// this function will be used by the drop down to filter the data based on the previous column value
function filterModels()
{
// bring the brand name from previous column
var brandName = $('#modelId').closest('td').prev('td').text();
// additional work in this sample to get the Id
var id = brandId(brandName);
// filter the data of the drop down list
var details= $.grep(models, function(n,i){
return n.brandId==id;
});
return details;
}
</script>
here a working demo
hope it will help you

Xamarin UI Test Android Date Picker (On Hold)

I'm working with Xamarin UI Test (1.0.0). I'm trying to write an extension method that will update the selected date.
Here is what I wrote so far. It works with iOS and Android 4.x. it does not work with Android 5.x.
public static void EnterDate(this IApp app, string datePickerStyleId, DateTime date)
{
var array = app.Query(datePickerStyleId);
if (array.Length == 0)
return;
foreach (var picker in array)
{
var newMonth = date.ToString("MMM");
var newDay = date.Day.ToString();
var newYear = date.Year.ToString();
if (app.IsAndroid())
{
app.Tap(picker.Label);
//if device OS > 5 try scrolll up
app.Repl();
app.Screenshot("Date Picker");
app.Tap("month");
app.EnterText(newMonth);
app.PressEnter();
app.Tap("day");
app.EnterText(newDay);
app.PressEnter();
app.Tap("year");
app.EnterText(newYear);
app.PressEnter();
app.ClickDone();
app.Screenshot("Page After Changing Date");
app.ClickButton("Ok");
}
else if (app.IsIOS())
{
app.Tap(picker.Id);
app.Screenshot("Date Picker");
var currentDate = picker.Text;
var split = currentDate.Split(' ');
var currentMonth = split[0];
var currentDay = split[1].Remove(split[1].Length - 1);
var currentYear = split[2];
if (!newMonth.Equals(currentMonth))
{
app.Tap(newMonth);
}
if (!newDay.Equals(currentDay))
{
app.Tap(newDay);
}
if (!newYear.Equals(currentYear))
{
app.Tap(newYear);
}
app.ClickButton("Done");
}
}
}
The problem that I'm running into is that I can't figure out how to select a certain date. App.ScrollUp()/.ScrollDown() do work to navigate to different months. Although, I haven't found to determine the current month and then pick a day. Here is the output from the tree command of the Repl() tool.
tree [[object CalabashRootView] > ... > FrameLayout] [FrameLayout] id: "content" [LinearLayout] id: "parentPanel" [FrameLayout] id: "customPanel" [FrameLayout] id: "custom" [DatePicker > LinearLayout] id: "datePicker" [LinearLayout] id: "day_picker_selector_layout"
[TextView] id: "date_picker_header" text: "Thursday"
[LinearLayout] id: "date_picker_month_day_year_layout"
[LinearLayout] id: "date_picker_month_and_day_layout", label: "August 6"
[TextView] id: "date_picker_month" text: "AUG"
[TextView] id: "date_picker_day" text: "6"
[TextView] id: "date_picker_year" text: "2015"
[AccessibleDateAnimator > ... > SimpleMonthView] id: "animator", label: "Month grid of days: August 6"
[LinearLayout] id: "buttonPanel"
[Button] id: "button2" text: "Cancel"
[Button] id: "button1" text: "OK"
Does anybody know or have a method to select the date for Xamarin UI test that will work on iOS and Android (4.x and 5.x)?

How to select menu item programmatically in Kendo menu

I have a menu with values and I want to add a Key shortcut that will select that item.
I can demonstrate in this fiddle exactly what I am looking for
function onSelect(e) {
var item = $(e.item),
menuElement = item.closest(".k-menu"),
dataItem = this.options.dataSource,
index = item.parentsUntil(menuElement, ".k-item").map(function () {
return $(this).index();
}).get().reverse();
index.push(item.index());
for (var i = -1, len = index.length; ++i < len;) {
dataItem = dataItem[index[i]];
dataItem = i < len-1 ? dataItem.items : dataItem;
}
alert(dataItem.value);
}
$(document).ready(function() {
$("#menu").kendoMenu({
dataSource: [
{
text: "Item 1 (A)",
value: "A",
items: [
{
text: "Sub Item 1 (L)",
value: "L",
items: [
{
text: "Sub Sub Item 1 (D)",
value: "D"
},
{
text: "Sub Sub Item 2 (E)",
value: "E"
}
]
},
{
text: "Sub Item 2 (O)",
value: "O"
}
]
},
{
text: "Item 2 (F)",
value: "F"
},
{
text: "Item 3 (G)",
value: "G"
}
],
select: onSelect
});
$(document.body).keydown(function (e) {
var menu = $("#menu").kendoMenu().data("kendoMenu");
if (e.altKey && e.keyCode == 76) {
alert("select item with value L");
// Pseudocode:
// var item = find item with value L
// menu.select(item); (or trigger)
}
});
});
I couldn't find anywhere any resources that could accomplish that. Also I can't assign ids to the rendered "li" via the datasource which makes it hard to select a node of the menu.
Any ideas?
Not sure if Kendo API supports triggering select item but I was able to achieve click the menu items with keyboard shortcuts using JQuery.
Check this JSFiddle
function clickMenuSpan(keyCode){
var shortcut = String.fromCharCode(keyCode);
$('#menu span.k-link').each(function(){
var txt = $(this).text();
if(txt.substr(-3) === '(' + shortcut + ')')
{
$(this).click();
}
})
}
You can use the above function in your keydown event. And add some filters to call this only for your array of shortcuts.
$(document.body).keydown(function (e) {
var menu = $("#menu").kendoMenu().data("kendoMenu");
if (e.altKey) {
clickMenuSpan(e.keyCode);
}
});

How to get kendo ui grid sort event?

I currently have a Kendo-UI grid. It has a few column where user can sort on, works great. I also have a details link on each row, so if the user clicks on this they are taken to a details page. I need to pass the current sort into the details page as a value. How can I get the current sort? is there an event I can bind to?
Thanks
You can get the sorting configuration whenever you want using sort method.
Example: Being grid the id of your Grid. Do:
// Get the grid object
var grid = $("#grid").data("kendoGrid");
// Get the datasource bound to the grid
var ds = grid.dataSource;
// Get current sorting
var sort = ds.sort();
// Display sorting fields and direction
if (sort) {
for (var i = 0; i < sort.length; i++) {
alert ("Field:" + sort[i].field + " direction:" + sort[i].dir);
}
} else {
alert("no sorting");
}
I ran into this need today and learned that the event is now present as of 2016 R3 release (2016.3.914).
Example usage:
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: { id: "id" }
}
},
sortable: true,
sort: function(e) {
console.log(e.sort.field);
console.log(e.sort.dir);
}
});
</script>
See: http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#events-sort

Resources