Kendo Grid: issue with DataType based Filter - kendo-grid

I have one data table and it contains columns of different datatype(e.g String, Date Time, Boolean and etc..), Following is code snippet that I have written in .cshtml file
#(Html.Kendo().Grid(Model.ViewResultTable)
.Name("Grid").Columns(columns =>
{
foreach (DataColumn column in Model.ViewResultTable.Columns.Cast<DataColumn>().Where(column => column.ColumnName != "XYZ"))
{
columns.Bound(typeof(DateTime) ,column.ColumnName).Title(column.ColumnName).Filterable(true).Width(120);
}
})
.Pageable(pageable => pageable
.PageSizes(new[] { 15, 20, 50, 100, 200, 500 })
.Messages(a => a.ItemsPerPage(""))
.PreviousNext(false)
.ButtonCount(5)
)
.Filterable(f => f.Extra(false))
.Groupable()
.ClientDetailTemplateId("template123")
.DataSource(
dataSource => dataSource
.Ajax()
.PageSize(15)
.ServerOperation(false)
)
.TableHtmlAttributes(new { #class= "grid" })
)
It takes all the type as string even defined type as "Date" or "Number". Does anyone having idea how to fix?

Related

How to update a json column of a table in laravel

I have below JSON values in the toys columns of the account table
{
"truck":{
"qty":10,
"price":53
},
"doll":{
"qty":15,
"price":15
}
}
Now I wantt add new values {"animals":{"qty":1,"price":4},"stickers":{"qty":12,"price":12}} to this. I have tried below method
$new_toys = [
'animals' => ['qty' => 1, 'price' => 4],
'stickers' => ['qty' => 12, 'price' => 12]
];
$old_tyoys = $account->toys;
array_push($old_tyoys, $new_toys);
$account->toys = $old_tyoys;
$account->save();
But this will update the column as below
{
"truck":{
"qty":10,
"price":53
},
"doll":{
"qty":15,
"price":15
},
"0":{
"animals":{
"qty":1,
"price":4
},
"stickers":{
"qty":12,
"price":12
}
}
}
But I want it as below
{
"truck":{
"qty":10,
"price":53
},
"doll":{
"qty":15,
"price":15
},
"animals":{
"qty":1,
"price":4
},
"stickers":{
"qty":12,
"price":12
}
}
What do I need to change in the code? Thanks
Replace array_push($old_tyoys, $new_toys); with collect($account->toys)->merge($new_toys)->all();
So your method code would become
$new_toys = [
'animals' => ['qty' => 1, 'price' => 4],
'stickers' => ['qty' => 12, 'price' => 12]
];
$merged = collect((array)$account->toys)->merge(new_toys)->all();
//Or
$merged = array_merge((array) $account->toys, $new_toys);
$account->toys = $merged;
$account->save();
That's because you're using array_push to aggregate the two objects, and internally it adds your second parameter as a value assigned to a numeric index 0. Try using array_merge.

Kendo.Grid does not send some data to the controller on "Create" operation

My Kendo.Grid need to perform CRUD operations on the data on SAVE CHANGES click
This is the Grid's definition:
#(Html.Kendo().Grid(Model.TicketReportPropertyList)
.Name("TicketReportPropertyGrid")
.Columns(columns =>
{
columns.Bound(c => c.ID).Hidden();
columns.Bound(c => c.PropertyName).Title("Property Name").EditorTemplateName("_PropertyNameEditor").Width(900);
columns.Bound(c => c.Amount).Title("Amount").Format("{0:C}").Width(90);
columns.Command(c => c.Custom("Delete").Click("DeleteRecord"));
})
.Events(events => events.DataBound("Databound").SaveChanges("SaveGrid").Edit("Edit"))
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell).DisplayDeleteConfirmation(false))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(c => c.ID);
model.Field(c => c.PropertyName);
model.Field(c => c.Amount);
})
.Events(events =>
{
events.RequestEnd("onRequestEnd");
})
.Read(read => read.Action("GetData", "TicketReportProperty", Model))
.Create(create => create.Action("AddTicketReportProperty", "TicketReportProperty"))
.Update(update => update.Action("UpdateTicketReportProperty", "TicketReportProperty"))
.Destroy(delete => delete.Action("DeleteTicketReportProperty", "TicketReportProperty"))
)
)
When doing the update, the following method of the controller is invoked:
[HttpPost]
public ActionResult UpdateTicketReportProperty([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<TicketReportPropertyEntity> ticketReportPropertyList)
{
TicketReportPropertyModel model = new TicketReportPropertyModel();
model = new TicketReportPropertyModel().UpdateTicketReportProperties(ticketReportPropertyList);
if (!model.Success)
{
ModelState.AddModelError("TicketReportProperty", model.ErrorDescription);
}
return Json(new[] { model.TicketReportPropertyList }.ToDataSourceResult(request, ModelState));
}
When Update is performed, all the data I need is populated inside of ticketReportPropertyList parameter and I can update the database
However, when performing a Create operation, the controller's method got hit, but ticketReportPropertyList is not populated with some of the parameters I need as happen during Update.
When adding new record the following method is invoked:
[HttpPost]
public ActionResult AddTicketReportProperty([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<TicketReportPropertyEntity> ticketReportPropertyList)
{
TicketReportPropertyModel model = new TicketReportPropertyModel();
model = new TicketReportPropertyModel().AddTicketReportProperty(ticketReportPropertyList);
if (!model.Success)
{
ModelState.AddModelError("TicketReportProperty", model.ErrorDescription);
}
return Json(new[] { model.TicketReportPropertyList }.ToDataSourceResult(request, ModelState));
}
This is TicketReportPropertyEntity:
public class TicketReportPropertyEntity
{
public int ID { get; set; }
public int TicketID { get; set; }
public decimal Amount { get; set; }
public string PropertyName { get; set; }
public int ReportPropertyID { get; set; }
}
What am I missing here?
I believe your issue can be fixed by simply replacing:
[Bind(Prefix = "models")]IEnumerable<TicketReportPropertyEntity> ticketReportPropertyList
with
TicketReportPropertyEntity ticketReportPropertyList
You are not sending a list when creating each row, you are simply sending one object.
OK, so for creates kendo initializes a new TicketReportPropertyList and then binds values from your columns. So your missing columns will be null. One mechanism to resolve that is to specify DefaultValue for those columns in your model definition. The value can come from a field in your model, a set value, value of a hidden, etc. So I typically have a model for the page the grid is displayed on with values for added items. Then I can do:
.Model(model =>
{
model.Id(c => c.ID);
model.Id(c => c.TicketID).DefaultValue(Model.TicketID);
model.Id(c => c.ReportPropertyID).DefaultValue(Model.ReportPropertyID);
model.Field(c => c.PropertyName);
model.Field(c => c.Amount);
})
Another way would be to handle the Grid's edit event, check for inserts and set the values:
if (e.model.isNew()) {
model.set("TicketID", $("#TicketID).val()); // hidden
model.set("ReportPropertyID", $("#ReportPropertyID).val()); // hidden
}

Monthpicker in Kendo UI for MVC works but sets current month when changing focus from grid cell

I have set up a "monthpicker" in a cell of a Kendo grid. The picker works fine and the column shows MMMM yyyy (e.g. April 2019)
However, when I move focus from the cell it doesn't set the cell as dirty and reverts back to current month and year.
Editor template (called Month.cshtml)
#model DateTime?
#{string[] formats = { "MMMM yyyy" }; }
#(Html.Kendo().DatePickerFor(m => m)
.Name("monthpicker")
.Start(CalendarView.Year)
.Depth(CalendarView.Year)
.Format("MMMM yyyy")
.DateInput()
.Culture("en-US")
.ParseFormats(formats)
.HtmlAttributes(new { style = "width: 100%", title = "monthpicker" })
)
Model:
[Display(Name = "Month", ResourceType = typeof(Resources.Resources))]
[UIHint("Month")]
public DateTime Month { get; set; }
View
#(Html.Kendo().Grid<GrindrodDataCapture.Models.MonthlyOceanPlan>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.Month).Format("{0:MMMM yyyy}");
//etc
})
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Sortable(sortable =>
{
sortable.SortMode(GridSortMode.SingleColumn);
})
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Events(events => events.Error("error_handler"))
.Sort(p => { p.Add("Month").Descending(); })
.Model(model => model.Id(p => p.ID))
.Read(read => read.Action("MonthlyOceanPlans_Read", "MonthlyOceanPlanGrid"))
.Create(create => create.Action("MonthlyOceanPlans_Create", "MonthlyOceanPlanGrid"))
.Update(update => update.Action("MonthlyOceanPlans_Update", "MonthlyOceanPlanGrid"))
.Destroy(destroy => destroy.Action("MonthlyOceanPlans_Destroy", "MonthlyOceanPlanGrid"))
)
I got a support response from Telerik which fixed it :)
"Hi Evan,
I noticed that the name of the date picker editor does not match the name of the field it edits. The editor is bound to its corresponding field of the model using the name setting. Currently the binder will try to bind the editor to the monthpicker field of the model. However, the actual field in the model is called Month.
Furthermore, when using a WidgetFor helper, you can omit the name configuration as the name is automatically set to the name of the field.
Could you pleas remove the Name configuration of the editor and let me know if the editor binds as expected?"

yii2 How to transfer post data from one view to two?

I am trying to create make a two-step form in yii2.
This is my SiteController.php
public function actionCreateCharacter()
{
$model = new Character();
var_dump(Yii::$app->request->post('Character'));
if ($model->load(Yii::$app->request->post())) {
$attributes=['imie','nazwisko','plec','wyznanie_id'];
if ($step1 = $model->validate($attributes)) {
//var_dump($step1);
// form inputs are valid, do something here
//var_dump(Yii::$app->request->post('Character');
return $this->render('createCharacterStep2', [
'model' => $model,
]);;
}
else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}
}
return $this->render('createCharacter', [
'model' => $model,
]);
}
public function actionCreateCharacterStep2()
{
$model2 = new Character();
var_dump($model);
if ($model2->load(Yii::$app->request->post())) {
var_dump(Yii::$app->request->post('Character'));
if ($model2->validate()) {
// form inputs are valid, do something here
return;
}
}
/*return $this->render('createCharacter2', [
'model' => $model,
]);*/
}
... and this is my Character.php (model + attributeLabels and tableName)
public function rules()
{
return [
[['user_id', 'imie', 'nazwisko', 'plec', 'wyznanie_id', 'avatar_src', 'avatar_svg'], 'required'],
[['user_id', 'wyznanie_id'], 'integer'],
[['avatar_svg'], 'string'],
[['imie'], 'string', 'max' => 15],
[['nazwisko'], 'string', 'max' => 20],
[['plec'], 'string', 'max' => 1],
[['avatar_src'], 'string', 'max' => 30]
];
}
I have access to $_POST by Yii::$app->request->post() in createCharacter - I get imie, nazwisko, plec and wyznanie_id.
But when I send the form in step 2 I have only post data from step 2.
How can I set the post data from step1+step2?
Sorry for my english and thanks in advance.
While rendering step2 from step1 action, you can always pass additional data to controller's action. So I added "STEPONEPOSTS" post variable which contains all posts of step 1. Check below.
public function actionCreateCharacter()
{
$model = new Character();
var_dump(Yii::$app->request->post('Character'));
if ($model->load(Yii::$app->request->post())) {
$attributes=['imie','nazwisko','plec','wyznanie_id'];
if ($step1 = $model->validate($attributes)) {
//var_dump($step1);
// form inputs are valid, do something here
//var_dump(Yii::$app->request->post('Character');
return $this->render('createCharacterStep2', [
'model' => $model,
'STEPONEPOSTS' => Yii::$app->request->post(),
]);;
}
else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}
}
return $this->render('createCharacter', [
'model' => $model,
]);
}
And now in step 2 view, you can get step 1 posts variable as
$STEPONEPOSTS
There is another way , if you have to table for step 1 and step 2. then save the data of step 1 first then step2 data. if you are not using two tables then you can create two form each form for each step and also create scenarios for each step according to the fields.I think this may help . You can use session also as per discussion in comments or you can use the extension array wizard but array wizard extension is not well documented , so i suggest you try my way i will help you.

how to get data from JSON without using script?

i want to get data from json file without using script code!
iam using MVC4 and want to put the code in the .cshtml file, how can i do this?
( Iam using kendo function)
example:
#{
ViewBag.Title = "Home Page";
}
<div class="chart-wrapper">
#(Html.Kendo().Chart()
.Name("chart")
.Title(title => title
.Text("Share of Internet Population Growth, 2007 - 2012")
.Position(ChartTitlePosition.Bottom))
.Legend(legend => legend
.Visible(false)
)
.DataSource(dataSource=>dataSource.Read(read=>read.Url("~/")))
.Events(e => e.SeriesClick("onSeriesHover"))
.Series(series => {
series.Pie(new dynamic[] {
new {category="Asia",value=53.8,color="#9de219"},
new {category="Europe",value=16.1,color="#90cc38"},
new {category="LatinAmerica",value=11.3,color="#068c35"},
new {category="Africa",value=9.6,color="#006634"},
new {category="MiddleEast",value=5.2,color="#004d38"},
new {category="NorthAmerica",value=3.6,color="#033939"}
})
.Labels(labels => labels
.Template("#= category #: #= value#%")
.Background("transparent")
.Visible(true)
.Color("Red")
)
.StartAngle(150);
})
.Tooltip(tooltip => tooltip
.Visible(true)
.Format("{0}%")
)
)
<script>
function onSeriesClick(e) {
alert(kendo.format("Series click :: {0} ({1}): {2}",
e.series.name, e.category, e.value));
}
</script>
</div>
i have use
.DataSource(dataSource=>dataSource.Read(read=>read.Url("~/")))
but not working
Try like this,
Example
View
#(Html.Kendo().Chart<Model.DashboardPieChartModel>()
.Name("PieChartPopup")
.Events(events => events.DataBound("onDataBound"))
.Legend(legend => legend
.Visible(false)
)
.DataSource(ds =>
{
ds.Read(read => read.Action("Read_PieChart", "Dashboard"));
}
)
.Series(series =>
{
series.Pie(
model => model.Percentage,
model => model.Service, null, null
).Labels(labels => labels
.Visible(true)
.Template("${ category } - ${ value }%")
).Overlay(ChartPieSeriesOverlay.None);
})
.Tooltip(tooltip => tooltip
.Visible(true)
.Template("${ category } - ${ value }%")
)
)
Controller
public JsonResult Read_PieChart()
{
//Whatever you do here
return Json(return your data);
}
Read this link: http://demos.kendoui.com/dataviz/pie-charts/remote-data.html