laravel 5.4 select2 multiple edit - jquery-select2

I don't know how to populate the edit function my select2 form. Here's my attempt on doing it. Controller:
public function edit($id)
{
$company = Company::find($id);
$categories = MainCategory::all();
$categories2 = array();
foreach ($categories as $category) {
$categories2[$category->main_cat_id] = $category->main_cat_name;
}
return view('company/edit_company')->with('company', $company)->with('categories', $categories2);
}
here's my view:
<select class="form-control select2-multi" name="company_main_cat[]" multiple="multiple" style="width: 50%" data-placeholder="select main category">
<option value='{{$category->main_cat_id}}'>{{$category->main_cat_name}}</option>
</select>
here's my JS:
<script type="text/javascript">
$('.select2-multi').select2();
$('.select2-multi').select2().val({!! json_encode($company->maincategories()->allRelatedIds()) !!}).trigger('change');
</script>

if you get your category data correctly to your view; Which seems to be an array from the code. You can foreach them inside your select element.
<select class="form-control select2-multi" name="company_main_cat[]" multiple="multiple" style="width: 50%" data-placeholder="select main category">
#foreach($category as $category_single)
<option value='{{$category_single->main_cat_id}}'>{{$category_single->main_cat_name}}</option>
#endforeach
</select>

Related

Dynamic Drowpdown on Select2 livewire laravel 8

I build a dynamic dropdown in select option but when i implement a select2 package it not work. Here is my code. The value of type not passing to the court select.
here is my Blade.php
{{$selectedType}}
<div class="row g-3 mb-3">
<div class="col-md">
<div class="form-floating" wire:ignore>
<select class="form-select" id="type" wire:model="selectedType" required>
<option value="">Select Court Type</option>
#foreach($types as $type)
<option value="{{$type->id}}">{{$type->court_type_name}}</option>
#endforeach
</select>
<label for="floatingInputGrid">Type</label>
</div>
</div>
#if (!is_null($courts))
<div class="col-md">
<div class="form-floating" wire:ignore>
<select class="form-select" wire:model="selectedCourt" required>
<option value="">Select Court Location</option>
#foreach($courts as $court)
<option value="{{$court->id}}">{{$court->court_name}}, {{$court->province}}</option>
#endforeach
</select>
<label for="floatingInputGrid">Court Location</label>
</div>
</div>
#endif
</div>
The livewire components works perfectly but in select2 it not work
public function render()
{
$types = Type::All();
$periods = Period::All();
return view('livewire.collection.add', compact('types', 'periods'));
}
public function updatedSelectedType($court_id)
{
$this->courts = Court::where('court_type', $court_id)->orderBy('court_name')->get();
}
public function updatedSelectedCourt($clerk_id)
{
$this->clerks = Clerk::where('court', $clerk_id)->get();
}
Select2
<script>
$(document).ready(function () {
$('.form-select').select2();
$('#type').on('change', function (e) {
var data = $('#type').select2("val");
#this.set('selectedType', data);
});
$('#court').on('change', function (e) {
var data = $('#court').select2("val");
#this.set('selectedCourt', data);
});
});
</script>
Nothing happen when clicked.
I solve select2 element in Livewire like this.
<div class="form-floating">
<select class="form-select" wire:model="selectedCourt">
<option value="">Select Court Location</option>
#foreach($courts as $court)
<option value="{{$court->id}}">{{$court->court_name}}</option>
#endforeach
</select>
<label for="floatingInputGrid">Court Location</label>
</div>
//
<script>
$(document).ready(function() {
window.initSelectDrop=()=>{
$('.form-select').select2({
placeholder: '{{ __('locale.Select') }}',
allowClear: true
});
initSelectDrop();
$('.form-select').on('change', function (e) {
livewire.emit('selectedItemCourt', e.target.value)
});
window.livewire.on('select2',()=>{
initSelectDrop();
});
});
</script>
in component
public function hydrate()
{
$this->emit('select2');
}
public $listeners = ['selectedItemCourt'];
//.....
public function selectedItemCourt($value)
{
dd($value);
$this->selectedCourt = $value;
}

getting empty list inside IActionResult on button submit - razor pages partial view

I am trying to pass a list of ids to IActionResult on button submit. The ids are coming from dropdown list selections. My view is a partial-view getting a model object. the problem is right now when i submit, the list is empty always.
I have read that we can not pass a list to controller! then what are the possible approaches, I am literally stuck on this for a day!
I have only pasted part of the code i felt is necessary to show,
please let me know if you want to see other code.
View.cshtml
<form method="post" asp-page-handler="UpdateComponent">
.
.
.
#{
var value1 = 0;
var value2 = 0;
var value3 =0;
}
<!-- asp-items="New plant SelectList"-->
<select class="form-control Shoplist News-plant-select_1 mt-2" data-search="true" asp-for="#value1">
<option value="">Bitte auswählen</option>
</select>
<br />
<!-- asp-items="New plant SelectList"-->
<select class="form-control Shoplist News-plant-select_2 mt-2" data-search="true" asp-for="#value2">
<option value="">Bitte auswählen</option>
</select>
<br />
<!-- asp-items="New plant SelectList"-->
<select class="form-control Shoplist News-plant-select_3 mt-2" data-search="true" asp-for="#value3">
<option value="">Bitte auswählen</option>
</select>
#{
Model.newsletterSubComponents.Add(new Models.NewsletterSubComponents() { NewPlantArticleId = value1 });
Model.newsletterSubComponents.Add(new Models.NewsletterSubComponents() { NewPlantArticleId = value2 });
Model.newsletterSubComponents.Add(new Models.NewsletterSubComponents() { NewPlantArticleId = value3 });
}
<input type="hidden" name="value1" value="#Model.newsletterSubComponents" asp-for="#Model.newsletterSubComponents"/>
.
.
.
<input type="submit" value="Speichern" class="btn btn-primary" />
</form>
controller
public IActionResult OnPostUpdateComponent(NewsletterComponents component, int? newsId, int? shortArticleId,
List<NewsletterSubComponents> newsletterSubComponents, int? test)
{
^
|
list empty
.
.
.
}
i populate dropdown lists using ajax
$.ajax(settings).done(function (data) {
$.each(data, function (index, element) {
$('.News-plant-select_1').append($("<option>").val(element.Id).text(element.NameGerman));
console.log(element.NameGerman);
$('.News-plant-select_2').append($("<option>").val(element.Id).text(element.NameGerman));
console.log(element.NameGerman);
});;
//remove spinner
$('.News-plant-select').removeClass("spinner-border");
});
If you want to receive ids, I think you can just use List< int > to receive it, also keep the parameter name the same as that in select element. I made an example based on your codes:
<form method="post" asp-page-handler="UpdateComponent">
#{
List<NewsletterSubComponents> newsletterSubComponents = new List<NewsletterSubComponents>
{
new NewsletterSubComponents{ NewPlantArticleId = 1, NewPlantArticleName = "AAA"},
new NewsletterSubComponents{ NewPlantArticleId = 2, NewPlantArticleName = "BBB"},
new NewsletterSubComponents{ NewPlantArticleId = 3, NewPlantArticleName = "CCC"}
};
var selectList = new SelectList(newsletterSubComponents, "NewPlantArticleId", "NewPlantArticleName");
}
<!-- asp-items="New plant SelectList"-->
<select name="newsletterSubComponentIds" class="form-control Shoplist News-plant-select_1 mt-2" data-search="true" asp-items="#selectList" >
<option value="">Bitte auswählen</option>
</select>
<br />
<!-- asp-items="New plant SelectList"-->
<select name="newsletterSubComponentIds" class="form-control Shoplist News-plant-select_2 mt-2" data-search="true" asp-items="#selectList">
<option value="">Bitte auswählen</option>
</select>
<br />
<!-- asp-items="New plant SelectList"-->
<select name="newsletterSubComponentIds" class="form-control Shoplist News-plant-select_3 mt-2" data-search="true" asp-items="#selectList">
<option value="">Bitte auswählen</option>
</select>
<input type="submit" value="Speichern" class="btn btn-primary" />
</form>
Result:

Select tag helper selected value not rendered in view

I need some help with my select tag helper.
I have an asp.net MVC View with a select 2 control as follows:
<div class="col-md-3">
<div class="form-group">
<label asp-for="NumberingType.Type" class="control-label" data-toggle="popover" data-placement="right" data-trigger="click" title="Field Help" data-content="Select the Numbering Scheme type that you want to create">Number Scheme Type *</label>
<select asp-for="NumberingType.TenantNumberingTypeId" asp-items="Model.NumberingType.NumberingTypeList" class="form-control select2">
<option></option>
</select>
<span asp-validation-for="NumberingType.TenantNumberingTypeId" class="text-danger"></span>
</div>
</div>
I am initialising the select2 as follows:
<script type="text/javascript">
$(document).ready(function () {
$(".select2").select2({
placeholder: "Select",
theme: 'bootstrap',
allowClear: true
});
});
</script>
I am loading the correct scripts:
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>
In my controller, I am populating the select 2 as follows:
public async Task<IActionResult> EditNumberScheme(int numberId)
{
var vm = new NumberingViewModel();
try
{
vm = await GetNumberingViewModel(numberId);
vm = UpdatedBaseViewModel<NumberingViewModel>(vm);
}
catch (Exception e)
{
await ErrorHandler.HandleException(e);
vm.MessageType = BaseViewModel.UserMessageType.Error;
}
return View(vm);
}
and
private async Task<NumberingViewModel> GetNumberingViewModel(int numberId)
{
var number = await DataGet.GetTenantNumberScheme(numberId);
NumberingViewModel model = new NumberingViewModel
{
Numbering = number
};
model.NumberingType = new TenantNumberingTypeModel();
model.NumberingType.NumberingTypeList = DataGet.GetTenantNumberingTypes().Result
.Select(x => new SelectListItem { Value = x.TenantNumberingTypeId.ToString(), Text = x.Type, Selected = (x.TenantNumberingTypeId == number.TenantNumberingTypeId) })
.ToList();
model.Owner = await DataGet.GetTenantOwner(UserInfo.Instance.Tenant.TenantId);
return model;
}
The select2 values are successfully loaded from the database and the selected value shows in the controller.
When placing a breakpoint at the select in the View, it is clear that the selected value is set as true in the NumberingTypeList.
Model.NumberingType.NumberTypeList = Count = 4
[1] = {Microsoft.AspNetCore.Mvc.Rendering.SelectListItem}
Disabled = false
Group = null
Selected = true
Text = "Credit Note"
Value = "2"
However the selected value is not rendered in the view.
<select class="form-control select2 select2-hidden-accessible" data-val="true" data-val-required="The TenantNumberingTypeId field is required." id="NumberingType_TenantNumberingTypeId" name="NumberingType.TenantNumberingTypeId" tabindex="-1" aria-hidden="true">
<option></option>
<option value="1">Invoice</option>
<option value="2">Credit Note</option>
<option value="3">Order</option>
<option value="4">Deposit</option>
</select>
Any help will be appreciated
Thanks
I managed to get this working by following this tutorial https://www.learnrazorpages.com/razor-pages/tag-helpers/select-tag-helper
It seems that the error is caused by the binding of the asp-for attribute. When I explicitly set the selected item in the controller as so:
model.NumberType = new TenantNumberingTypeModel();
model.NumberType.NumberSchemeList = DataGet.GetTenantNumberingTypes().Result
.Select(x => new SelectListItem { Value = x.TenantNumberingTypeId.ToString(), Text = x.Type })
.ToList();
model.NumberingType.TenantNumberingTypeId = number.TenantNumberingTypeId;
number being the object retrieved from the database
then it works correctly and the asp-items automatically selects the value that is represented by the asp-for attribute.
<select class="form-control select2 select2-hidden-accessible" data-val="true" data-val-required="Please select a type" id="NumberType_NumberTypeId" name="NumberType.NumberTypeId" tabindex="-1" aria-hidden="true">
<option></option>
<option value="1">Invoice</option>
<option selected="selected" value="2">Credit Note</option>
<option value="3">Order</option>
<option value="4">Deposit</option>
</select>
Hope this helps someone
That is the example of the visibility, you must use "select2.full.min.js".

Cascade drop-down in MVC View without ajax?

I created one View Model with two Entities. I am passing this view model to my MVC Razor view which have two html drop-downs for each entity respectively.
<select class="form-control" id="Employees" name="Employees">
#foreach (var employee in Model.Employees)
{
<option value="#employee.Id"> #employee.name </option>
}
</select>
<select class="form-control" id="Tasks" name="Tasks">
#foreach (var task in Model.Tasks)
{
<option value="#task.Id"> #task.name </option>
}
</select>
Employee table is the parent of Task table. What I want is getting all the tasks which are related to particular employee only. e.g. In Employee drop-down I select John, then in Tasks drop-down I should get all the tasks which are relative to John. I know how to do this with ajax. I am looking for some other solution.
Is it possible to do something like this:
#foreach (var task in Model.Tasks.Where(x=>x.employeeId == 'Selected in previous dropdown'))
{
<option value="#task.Id"> #task.name </option>
}
Html block
<select id="Employees">
<option value="">Select Employee</option>
<option value="1">Employee1</option>
<option value="2">Employee2</option>
</select>
<select id="Tasks">
<option value="">Select Task</option>
<option value="1" data-employee="1">Employee1Task1</option>
<option value="2" data-employee="1">Employee1Task2</option>
<option value="3" data-employee="1">Employee1Task3</option>
<option value="1" data-employee="2">Employee2Task1</option>
<option value="2" data-employee="2">Employee2Task2</option>
<option value="3" data-employee="2">Employee2Task3</option>
</select>
Script scetion
<script>
$(document).ready(function () {
//on page ready hide all task option
$("#Tasks").find('option').hide();
// set task as empty
$("#Tasks").val('');
// onchange of employee Drop down
$("#Employees").on('change', function () {
var selectedEmployee = $("#Employees").val();
if (selectedEmployee != '') {
$("#Tasks").find('option').hide();
$("#Tasks option[value='']").show();
$('*[data-employee="' + selectedEmployee + '"]').show();
}
else {
// if employee not selected then hide all tasks
$("#Tasks").find('option').hide();
$("#Tasks").val('');
}
});
});
</script>
Please populate country and state drop down list using MVC way by for each loop and use above script. The mandatory case is you have to render all cascade options
<select class="form-control" id="Employees" name="Employees">
#foreach (var employee in Model.Employees)
{
<option value="#employee.Id"> #employee.name </option>
}
</select>
<select class="form-control" id="Tasks" name="Tasks">
#foreach (var task in Model.Tasks)
{
<option value="#task.Id" data-employee="#task.EmployeeId"> #task.name </option>
}
</select>

changes to &nbsp in asp.net mvc html.dropdownlist

I want to show items with indention in html.dropdownlist
this is code in controller
IEnumerable<ViewModels.testvm> test = db.Database.SqlQuery<ViewModels.testvm>(#"WITH tree (id, parentid, level, title, rn) as
(
some code
)
***********SELECT id,REPLICATE(' ',level) + title as title
FROM tree
order by RN");
ViewBag.ParentID = new SelectList(test, "ID", "Title");
as you can see I add &nbsp to dropdown items in replecate
but the problem is &nbsp shows in dropdown.
this is view > source result:
<select class="form-control" id="ParentID" name="ParentID"><option
value="10">Menu1</option>
<option value="11">&nbsp;Sub1</option>
<option value="14">&nbsp;Submenu1</option>
<option value="12">Menu2</option>
<option value="16">&nbsp;sub2</option>
<option value="13">Menu3</option>
<option value="15">&nbsp;sub3</option>
<option value="17">&nbsp;&nbsp;sub sub</option>
<option value="22">&nbsp;&nbsp;&nbsp;sub3 sub sub</option>
<option value="19">menu4</option>
<option value="20">&nbsp;sub4</option>
<option value="21">menu5</option>
</select>
as you can see converted to &nbsp;
I tried "\xA0" instead of &nbsp but it shows in dropdown too!
I think html.raw can solve this, but I don't know how can I use it with html.dropdownlist.
this is view
<div class="col-md-10">
#Html.DropDownList( "ParentID", null, htmlAttributes: new { #class = "form-
control" })
</div>
any Idea?
Edit
by changing view like this the problem solved:
I tried this after checked a post as answer
<select class="form-control" id="ParentID" name="ParentID">
<option value="0">First Level</option>
#foreach (var item in ViewBag.ParentID)
{
<option value="#item.Value">#Html.Raw(#item.Text)</option>
}
</select>
You can manually create the dropdown list assuming you place your collection in a ViewModel member called ParentIDs:
The View:
#if (Model.ParentIDs.Any())
{
<select class="form-control" id="ParentID" name="ParentID">
#foreach (var item in Model.ParentIDs)
{
if (Model.ParentID == item.id)
{
<option value="#item.id" selected>#item.title</option>
}
else
{
<option value="#item.id">#item.title</option>
}
}
</select>
}

Resources