MVC Kendo Combobox set value from the DataSource - kendo-grid

I have this code, how can I set the Value property to the first element within the DataSource?
#(Html.Kendo().ComboBox()
.Name("cboShip")
.Placeholder("Select Ship...")
.Filter(FilterType.Contains)
.DataTextField("ShipName")
.DataValueField("ShipId")
.DataSource(s =>
{
s.Read(read => { read.Action("GetShips", "Filter"); });
})
.Events(events => events.Change("cboShipMultiChange"))
.Value('' /*????? I want to get the first element from the DataSource and use it in here*/)
)

from my comments:
you should be able to just apply .SelectedIndex (0) rather than a value. in the declaration
#(Html.Kendo().ComboBox()
.SelectedIndex(0) //or whatever index you want to apply.
....... removed for brevity
)

Related

Kendo MVC Grid Filtering - Filters that consider multiple fields

I have a MVC Kendo grid where one column is a client template that actually uses multiple fields. By default the built in filtering is only applied to the field the column is bound to. How do I override that so it considers both fields. Ie, when I search for "Contains" "De" a column that displays "Detroit, MI" should return.
Here's what I have so far:
MVC View
#(Html.Kendo().Grid<ViewModel>()
.DataSource(dataSource => dataSource
.Custom()
.Transport(t =>
{
t.Read(r => r.Action("StatusGridRead", "DeviceStatus"));
})
.Schema(schema => schema
.Data("Result.Data")
.Total("Result.Total")
.Errors("Result.Errors")
.Model(m =>
{
m.Id(f => f.Id);
m.Field(f => f.StateOrProvince);
m.Field(f => f.City);
...
})
)
)
.Columns(columns =>
{
columns.Bound(c => c.StateOrProvince).Title("City & State").ClientTemplate("#=City#, #=StateOrProvince#");
...
})
.Events(e=>
{
e.Filter("statusGridFilter");
})
.Sortable()
.Filterable(f =>
{
f.Extra(false);
f.Operators(o => o.ForString(s =>
{
s.Clear();
s.Contains("Contains");
s.IsEqualTo("Is Equal To");
s.StartsWith("Starts With");
s.EndsWith("Ends With");
s.DoesNotContain("Does Not Contain");
s.IsNotEqualTo("Is Not Equal To");
}));
})
)
Javascript
function statusGridFilter(e) {
if (e.field == "StateOrProvince") {
//What do I do here?
}
}
I understand if I made a column for city and one for state that would resolve this issue, however I actually have a similar scenario (client template with many string fields displayed) where that won't work and am just picking this as the easiest example. Other than making 1 column for 1 field, I'm open to any other ideas that may solve filtering for this scenario.

Unable to add new key-value pair dynamically to a STATE JSON Array in React App

I am trying to add a new key-value pair to the already loaded JSON Array. I am adding the new key-value pair to customize the header column cells in react bootstrap table but getting the below errors. Can any one please help?
'Columns' in the below state is where I wanted to add new key-value pair
state = {
data: MYResult.Products || [],
actualData: MYResult.Products || [],
columns: MYResult.ParametricList_Attributes || [],
isCompareClicked: false,
isDisabled: true,
selected: []
};
This is how I am adding the key-value pair -
componentDidMount(){
checkbox = (column, colIndex) => {
return (
<h5>{ column.text }<checkbox/></h5>
);
}
console.log(this.state.columns) ;
newColumn = this.state.columns.map((column) => {
return {...column, headerFormatter: checkbox};
});
this.setState({columns: newColumn });
}
Full code here - https://codesandbox.io/s/o1r988qkz Please uncomment the componentDidMount() to see the issue
Firstly, there's a typo in dcolumn and column.
And regarding the not defined error, you need to define it using const. Use like:
const checkbox = (column, colIndex) => {
return (
<h5>{column.text}<checkbox /></h5>
);
}
JavaScript variables need to be declared when they are used. Public class syntax can not be used everywhere. The error you're getting is self-evident - 'checkbox is not defined'.
Refer this on how to use it: https://tylermcginnis.com/javascript-private-and-public-class-fields/
I simply declared the undeclared variables in your example and the code worked.

Yii2: Kartik Select2: Initial Value from Model Attribute

I have a Model who has a column (attribute) that stored a comma separated value of IDs.
For Example,
Movie has a column "Genre" that includes more than one genre, e.g.: 40,20,1,3
How can I use Select2 widget to show these values separated when 'multiple' => true
And how can I save them back into comma-separated value as a string. I want a solution that will allow for quick flexibility. I know you can implode and explode the string but seems too much.
Any help appreciated
If I remember correctly pass the default option as part of the $options configuration for the widget:
echo $form->field($model, 'model_attribute_name')->widget(Select2::className(), [
'data' => $data
'options' => [
'class' => 'form-control',
'placeholder' => 'Choose Option...',
'selected' => 40
],
'pluginOptions' => [
'allowClear' => true,
],
])->label('Select2 Form Field');
This is from memory for grain fo salt here. The documentation at http://demos.krajee.com/widget-details/select2 is not very specific about how to do this.
I don't believe you can do that. Select2 sends the data in post as an array, so you would still need to use implode before saving. What i would do instead is in your model class:
class MyModel extends \yii\db\ActiveRecord {
$public myArrayAttribute;
...
public function beforeSave($insert) {
if (parent::beforeSave($insert)) {
$this->myAttribute = implode(',', $this->myArrayAttribute);
return true;
}
return false;
}
public function afterFind() {
parent::afterFind();
$this->myArrayAttribute = explode(',', $this->myAttribute);
}
}
This way myArrayAttribute will hold the values from the comma separated field as an array. Of course you will need to add validation rules for it and use it instead of your other attribute in create and update forms.
if you're displaying a form with already populated fields, maybe you want to update an already existing object, and you want to display the already saved value for the Select2 field, use 'data' => [ 1 => 'Some value' ], where 1 is the value, associated to the value displayed in the form. You can retrieve stuff to put in data from DB beforehand.
Source: https://github.com/kartik-v/yii2-widget-select2/issues/37

How can I ensure Kendo Grid passes a numeric value with the correct separator to ASP.NET MVC?

I have a simple grid that uses a custom popup editor template. In the template, I'd like to use a Numeric Textbox.
Due to localization, the application keeps trying to use a comma to separate decimals in the numeric values. When these values are passed to the ASP.NET MVC back-end, the value is lost and null is passed. How can I ensure the posted value has a period separator?
I have tried setting the underlying field values to 2.5 instead of 2,5 in the grid's Save event, as well as tried to overwrite the e.model.WeightKg to 2.5. The value is still passed with a comma separator, as shown by inspecting the form data in the request.
My grid:
#(Html.Kendo().Grid<PackageViewModel>()
.Name("PackageGrid")
.Columns(columns => {
columns.Bound(o => o.PackageCode);
columns.Bound(o => o.WeightKg);
columns.Command(o => o.Edit());
})
.DataSource(d => d
.WebApi()
.Model(m => m.Id(o => o.PackageCode))
.Read(c => c.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Packages" })))
.Create(c => c.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Packages" })))
.Destroy(c => c.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Packages" id = "{0}" })))
.Update(c => c.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Packages" id = "{0}" })))
.PageSize(20)
)
.Editable(e => e.Mode(GridEditMode.PopUp).TemplateName("Package"))
.Selectable()
.Deferred()
)
The numeric textbox in the template:
#Html.Kendo().NumericTextBoxFor(m => m.WeightKg).Decimals(8)
And finally, the unparsed form data, followed by the parsed form data:
sort=&group=&filter=&PackageCode=DOOS-B&WeightKg=2%2C5
sort:
group:
filter:
PackageCode:DOOS-B
WeightKg:2,5

Changing value of an attribute in DetailView widget

I have a table named Play and I'm showing details of each record in Yii2 detail view widget. I have an attribute in that table recurring which is of type tinyint, it can be 0 or 1. But I don't want to view it as a number, instead i want to display yes or no based on the value (0 or 1).
I'm trying to change that with a function in detailview widget but I'm getting an error: Object of class Closure could not be converted to string
My detail view code:
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'name',
'max_people_count',
'type',
[
'attribute' => 'recurring',
'format'=>'raw',
'value'=> function ($model) {
if($model->recurring == 1)
{
return 'yes';
}
else {
return 'no';
}
},
],
'day',
'time',
...
Any help would be appreciated !
Unlike GridView which processes a set of models, DetailView processes just one. So there is no need for using closure since $model is the only one model for display and available in view as variable.
You can definitely use solution suggested by rkm, but there is more simple option.
By the way you can simplify condition a bit since the allowed values are only 0 and 1:
'value' => $model->recurring ? 'yes' : 'no'
If you only want to display value as boolean, you can add formatter suffix with colon:
'recurring:boolean',
'format' => 'raw' is redundant here because it's just text without html.
If you want add more options, you can use this:
[
'attribute' => 'recurring',
'format' => 'boolean',
// Other options
],
Using formatter is more flexible approach because these labels will be generated depending on application language set in config.
Official documentation:
DetailView $attributes property
Formatter class
Formatter asBoolean() method
See also this question, it's quite similar to yours.
Try
'value' => $model->recurring == 1 ? 'yes' : 'no'