How to filter multiple form fields and display in table in angular 5? - angular5

I have a form which has checkbox and dropdowns and the data which is present in dropdowns is fetched from json. I have to select the dropdowns option , text written in text box on click of submit i have to filter and show the filtered data in table.
<form [formGroup]="reportsForm" (ngSubmit)=onSubmit(reportsForm.value)>
<label> Task Status</label>
<div>
<label class="checkbox-inline"></label>
<input type="checkbox" formControlName="whole" id="whole" value="whole"> a
<label class="checkbox-inline"></label>
<input type="checkbox" formControlName = "progress" id= "progress" value="progress"> b
</div>
<label>Date Time (GMT)</label>
<div class="">
<div class="col-md-6">
<label>FROM</label>
<input type="date" formControlName = "bfrom" id= "from" class="form-control">
</div>
<div class="col-md-6">
<label>TO</label>
<input type="date" formControlName = "to" id= "to" class="form-control">
</div>
</div>
<label>Group Name</label>
<div class="input-group-btn">
<select class="form-control" formControlName="groupname" id="groupname">
<option>Select</option>
<option *ngFor="let x of y" >{{x.grouping}}</option>
</select>
</div>
<label>Task Name</label>
<div class="input-group-btn">
<input type="text" formControlName="taskname" id="taskname" class="form-control">
</div>
<label>ASSIGNEE</label>
<div class="input-group-btn">
<select class="form-control" formControlName="assignee" id="assignee">
<option>Select</option>
<option *ngFor="let x of y" >{{x.assignee}}</option>
</select>
</div>
<label>Frequency</label>
<div class="input-group-btn">
<select class="form-control" formControlName="frequency" id= "frequency">
<option>Select</option>
<option *ngFor="let x of y">{{x.frequency}}</option>
</select>
</div>
<div class="buttons">
<button type="submit" class="btn">Submit</button>
</div>
</form>
<table class="table table table-bordered">
<thead>
<tr>
<th scope="col ">GroupName</th>
<th scope="col ">Assignee</th>
<th scope="col ">frequency</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let x of y">
<td scope="col">{{x.grouping}}</td>
<td scope="col">{{x.assignee}}</td>
<td scope="col">{{x.frequency}}</td>
</tr>
</tbody>
</table>
I have created a form in my component I have created all form data which is populating on submit of my form based on my selections of dropdowns and checkbox. And I have to filter those data and display on the table on form submit
#Component({
selector: 'app-rep',
templateUrl: './rep.component.html',
styleUrls: ['./rep.component.css']
})
export class RepComponent implements OnInit {
y;
users;
reportsForm: FormGroup;
constructor(private service: RepositoryService) { }
ngOnInit() {
this.reportsForm = new FormGroup({
whole: new FormControl(''),
progress: new FormControl(''),
bfrom: new FormControl(''),
to: new FormControl(''),
groupname: new FormControl(''),
taskname: new FormControl(''),
assignee: new FormControl(''),
frequency: new FormControl(''),
});
this.getTasks();
this.getUsers();
}
public getUsers() {
this.service.getData(usersUrl).subscribe(res =>{this.users = res.data.items});
}
public getTasks() {
this.service.getData(reportsUrl).subscribe(res =>{this.y= res.data.items});
}
onSubmit(filterValue:any) {
console.log(this.reportsForm);
}
}

Finally I came up with one solution which is working for multiple filters and on submit data should be filtered in a table. But it needs optimization if you have many conditions.
onSubmit() {
this.filteredtasks=[];
let grp = this.reportsForm.value.groupname;
let fre = this.reportsForm.value.frequency;
let as= this.reportsForm.value.assignee;
let tsknm = this.reportsForm.value.taskname;
for(let i=0; i< this.y.length; i++) {
if(
(grp == "" || grp == this.tasks[i].groupname) &&
(fre == "" || fre == this.tasks[i].frequency) &&
(as== "" || as== this.tasks[i].assignee) &&
(tsknm == "" || tsknm == this.tasks[i].taskname)
) {
this.filteredtasks.push(this.y[i]);
}
}
The filteredtasks array is having the filtered list..
<table class="table table table-bordered">
<thead>
<tr>
<th scope="col ">GroupName</th>
<th scope="col ">Assignee</th>
<th scope="col ">frequency</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let x of filteredtasks">
<td scope="col">{{x.groupname}}</td>
<td scope="col">{{x.assignee}}</td>
<td scope="col">{{x.frequency}}</td>
</tr>
</tbody>
</table>

Related

ASP .NET core Razor page - Avoid refreshing the page

I have tow buttons in one Form, first button for add website info to a local table and second button for add social media info to another table, after all info added locally,
then I can click on 'add all info' button for add all info in same time to database.
My question is how can I add info to a table without refreshing the page?
AddAllInfo.cshtml:
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewWebSiteInfo.websiteName">Website URL</label>
<input type="text" asp-for="NewWebSiteInfo.websiteName" class="form-control" />
</div>
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewWebSiteInfo.websiteUrl">Website URL</label>
<input type="text" asp-for="NewWebSiteInfo.websiteUrl" class="form-control" />
</div>
<button type="submit" validatedisable="True" asp-page-handler="AddWebsiteInfo" class="btn btn-primary" >Add Website info</button>
<div class="mb-3">
#if (AddInfoModel.WebSitelist.Count > 0)
{
<div class="col-12 border p-3">
<table class="table table-striped table-bordered">
<thead style="background-color:lightgray">
<tr>
<th>WebsiteName</th>
<th>websiteURL</th>
</tr>
</thead>
<tbody>
#foreach (Website item in AddAllInfoModel.WebSitelist)
{
<tr>
<td>#item.WebsiteName</td>
<td>#item.websiteURL</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
</br>
</br>
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewSocialMediaInfo.SocialMediaName">Social Media</label>
<input type="text" asp-for="NewSocialMediaInfo.SocialMediaName" class="form-control" />
</div>
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewSocialMediaInfo.SocialMediaAccount">Account</label>
<input type="text" asp-for="NewSocialMediaInfo.SocialMediaAccount" class="form-control" />
</div>
<button type="submit" validatedisable="True" asp-page-handler="AddSocialMediaInfo" class="btn btn-primary" >Add socil Media info</button>
<div class="mb-3">
#if (AddInfoModel.SocialMedialist.Count > 0)
{
<div class="col-12 border p-3">
<table class="table table-striped table-bordered">
<thead style="background-color:lightgray">
<tr>
<th>SocialMediaName</th>
<th>SocialMediaAccount</th>
</tr>
</thead>
<tbody>
#foreach (SocialMedia item in AddAllInfoModel.SocialMedialist)
{
<tr>
<td>#item.SocialMediaName</td>
<td>#item.SocialMediaAccount</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
</br>
<div class="col-4 offset-2">
<button type="submit" class="btn btn-primary form-control"> Add all info </button>
</div>
</form> ```
AddAllInfo.cshtml.cs:
public void OnPostAddSocialMediaInfo()
{
SocialMedialist.Add(new SocialMedia { SocialMediaName = NewSocialMediaInfo.SocialMediaName,
SocialMediaAccount=NewSocialMediaInfo.SocialMediaAccount});
}
public void OnPostAddWebsiteInfo()
{
WebSitelist.Add(new WebSite { WebSiteName = NewWebSiteInfo.WebsiteName,
websiteUrl =NewWebSiteInfo.websiteUrl});
}
You can use js to pass data to handler,and then use js to add html to tbody,here is a demo to add data to table without refresh the page:
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewWebSiteInfo.websiteName">Website URL</label>
<input type="text" asp-for="NewWebSiteInfo.websiteName" class="form-control" />
</div>
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewWebSiteInfo.websiteUrl">Website URL</label>
<input type="text" asp-for="NewWebSiteInfo.websiteUrl" class="form-control" />
</div>
<input type="button" onclick="AddWebsiteInfo()" class="btn btn-primary" value="Add Website info">
<div class="mb-3">
#if (AddInfoModel.WebSitelist.Count > 0)
{
<div class="col-12 border p-3">
<table class="table table-striped table-bordered">
<thead style="background-color:lightgray">
<tr>
<th>WebsiteName</th>
<th>websiteURL</th>
</tr>
</thead>
<tbody>
#foreach (Website item in AddAllInfoModel.WebSitelist)
{
<tr>
<td>#item.WebsiteName</td>
<td>#item.websiteURL</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
</br>
</br>
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewSocialMediaInfo.SocialMediaName">Social Media</label>
<input type="text" asp-for="NewSocialMediaInfo.SocialMediaName" class="form-control" />
</div>
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewSocialMediaInfo.SocialMediaAccount">Account</label>
<input type="text" asp-for="NewSocialMediaInfo.SocialMediaAccount" class="form-control" />
</div>
<input type="button" onclick="AddSocialMediaInfo()" class="btn btn-primary" value="Add socil Media info">
<div class="mb-3">
#if (AddInfoModel.SocialMedialist.Count > 0)
{
<div class="col-12 border p-3">
<table class="table table-striped table-bordered">
<thead style="background-color:lightgray">
<tr>
<th>SocialMediaName</th>
<th>SocialMediaAccount</th>
</tr>
</thead>
<tbody>
#foreach (SocialMedia item in AddAllInfoModel.SocialMedialist)
{
<tr>
<td>#item.SocialMediaName</td>
<td>#item.SocialMediaAccount</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
</br>
<div class="col-4 offset-2">
<input type="button" onclick="AddAllInfo()" class="btn btn-primary" value="Add all info">
</div>
</form> ```
js:
#section Scripts{
<script>
function AddWebsiteInfo() {
var NewWebSiteInfo = {
'websiteName': $("#NewWebSiteInfo_websiteName").val(),
'websiteUrl': $("#NewWebSiteInfo_websiteUrl").val()
};
$.ajax({
type: 'POST',
url: '?handler=AddWebsiteInfo',
data: NewWebSiteInfo,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
dataType: 'json',
success: function (data) {
var html = "<tr><td>" + data.websiteName + "</td><td>" + data.websiteUrl + "</td></tr>";
$("tbody")[0].innerHTML = $("tbody")[0].innerHTML + html;
}
});
}
function AddSocialMediaInfo() {
var NewAddSocialMediaInfo = {
'SocialMediaName': $("#NewSocialMediaInfo_SocialMediaName").val(),
'SocialMediaAccount': $("#NewSocialMediaInfo_SocialMediaAccount").val()
};
$.ajax({
type: 'POST',
url: '?handler=AddSocialMediaInfo',
data: NewAddSocialMediaInfo,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
dataType: 'json',
success: function (data) {
var html = "<tr><td>" + data.socialMediaName + "</td><td>" + data.socialMediaAccount + "</td></tr>";
$("tbody")[1].innerHTML = $("tbody")[1].innerHTML + html;
}
});
}
function AddAllInfo() {
AddWebsiteInfo();
AddSocialMediaInfo();
}
</script>
}
handler:
[BindProperty]
public WebSiteInfo NewWebSiteInfo { get; set; }
[BindProperty]
public SocialMediaInfo NewSocialMediaInfo { get; set; }
public void OnGet()
{
}
public JsonResult OnPostAddWebsiteInfo()
{
WebSitelist.Add(new WebSite { WebSiteName = NewWebSiteInfo.WebsiteName,
websiteUrl =NewWebSiteInfo.websiteUrl});
return new JsonResult(NewWebSiteInfo);
}
public JsonResult OnPostAddSocialMediaInfo()
{
SocialMedialist.Add(new SocialMedia { SocialMediaName = NewSocialMediaInfo.SocialMediaName,
SocialMediaAccount=NewSocialMediaInfo.SocialMediaAccount});
return new JsonResult(NewSocialMediaInfo);
}
The best way to do this is to run the post request in javascript, this will not refresh the page.
2nd option is by calling the get method again at the end of the post method and then passing the model with the data to the get. So that when the page refreshes the data is filled in again

Validating dynamic array in vuelidate

I am very new to vue and I am trying to validate an array using vuelidate which is used to render a dynamic table. The problem is with the validation() method as I can comprehend.
According to vuelidate docs, https://vuelidate.js.org/#sub-collections-validation, the $each method supports array. When I use it, the validation never fails. However, when I omit $each, and, try to validate first index of the array, it returns as corrected - validation fails.
To be more precise, I am trying to validate each added row(s), and if there's a problem with the validation, it'd add a class to the affected row.
Component App.vue,
This is the HTML code:
<template>
<div>
<br>
<div class="text-center">
<button type="button" class="btn btn-outline-primary" #click="addRow()">Shto</button>
</div>
<br>
<p
v-for="error of v$.$errors"
:key="error.$uid"
>
<strong>{{ error.$validator }}</strong>
<small> on property</small>
<strong>{{ error.$property }}</strong>
<small> says:</small>
<strong>{{ error.$message }}</strong>
</p>
<form name="articles" #submit.prevent="submitForm">
<table class="table table-hover table-responsive">
<thead class="thead-inverse">
<tr>
<th>Nr.</th>
<th class="col-3">Numri</th>
<th class="col-4">Përshkrimi</th>
<th class="col-1">Sasia</th>
<th class="col-1">Çmimi</th>
<th class="col-2">Shuma</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="(item, idx) in items_table" :key="item">
<td>
{{idx+1}}
</td>
<td>
<input v-model="item.part_no" name="part_no[]" class="form-control" type="text" />
</td>
<td>
<textarea v-model="item.part_name" name="part_name[]" class="form-control" type="text"></textarea>
</td>
<td>
<input v-model="item.part_qty" name="part_qty[]" class="form-control " type="number" step="0.01">
</td>
<td>
<input v-model="item.part_price" name="part_price[]" class="form-control" type="number" step="0.01">
</td>
<td>
<input :value="item.part_total" name="part_total[]" class="form-control text-center border-0" style="background-color: transparent; font-size: 18 px;" type="text" disabled>
</td>
<td>
<button type="button" #click="deleteRow(idx)" class="btn btn-danger btn-md btn-block">X</button>
</td>
</tr>
</tbody>
</table>
<div class="text-center">
<button type="submit" name="" id="" class="btn btn-primary btn-lg btn-block">Valido</button>
</div>
</form>
<div class="text-center">
<textarea name="" id="verbose_log" cols="70" rows="15" refs="logg"></textarea>
</div>
</div>
</template>
This is the content from script tag:
<script>
import useVuelidate from '#vuelidate/core'
import { required } from '#vuelidate/validators'
export default {
name: 'App',
setup: () => ({ v$: useVuelidate() }),
validation() {
return {
items_table: {
$each: {
part_no: {
required,
}
}
},
}
},
data() {
return {
items_table: [
{
part_no: '', part_name: '', part_qty: '', part_price: '', part_total: ''
}
],
items_subtotal: 0.00,
items_total: 0.00,
}
},
methods: {
deleteRow(index) {
if(this.items_table.length == 1) {
this.items_table.splice(index, 1);
this.items_subtotal = 0.00;
this.items_total = 0.00;
this.addRow();
} else if(this.items_table.length > 0) {
this.items_table.splice(index, 1);
}
},
addRow() {
this.items_table.push({part_no: '', part_name: '', part_qty: '', part_price: '', part_total: ''});
},
submitForm() {
this.v$.$touch();
//if (this.v$.$error) return;
console.log(this.v$);
document.getElementById('verbose_log').innerHTML = JSON.stringify(this.$data, null, 4);
}
},
computed: {
//
}
}
</script>
For the sake of clarity, I have excluded two methods which calculate line total and the total itself.

Getting a NaN when typing a value

I'm trying to calculate a value from 2 input boxes and then get the total of those input boxes. I'm then trying to get the all my amounts and total them and add them to the subtotal but the issue I'm having is that when I type in a number in the first box my output is NaN instead of 0 and I would like for it to show me a 0 instead.
Here is my code
<template>
<div class="content-header">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-lg-12">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Unit</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products">
<td>{{ product['name'] }}</td>
<td>
<input type="text" class="form-control" v-model="unit[product['unit']]" #change="calculateCost(product['name'])">
</td>
<td>
<input type="text" class="form-control" v-model="price[product['price']]" #change="calculateCost(product['name'])">
</td>
<td>
{{ cost[product['name']] }}
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>
Subtotal: {{ subTotal }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default{
props: [],
data(){
return {
products: [],
unit: {},
price: {},
cost: []
}
},
computed:{
subTotal(){
if(this.cost!== null)
{
if(Object.keys(this.cost).length !== 0){
return Object.keys(this.cost).reduce((carry, item) => {
carry+= Number(this.cost[item])
return carry;
}, Number(0))
}else{
return 0;
}
}
}
},
methods: {
getProducts(){
axios.get(`/api/product/all`).then(response => {
this.products = response.data.products;
});
},
calculateCost(item){
this.cost[item] = Number(this.unit[item]) * Number(this.price[item]);
},
},
mounted() {
this.getProducts();
}
}
</script>
Almost all type of inputs return a string. You can use
<input type="number" class="form-control" v-model="unit[product['unit']]" #change="calculateCost(product['name'])">
or
<input type="text" class="form-control" v-model.number="unit[product['unit']]" #change="calculateCost(product['name'])">
The problem is the v-model for unit and price are set to the different keys than the one given to calculateCost(), which causes the lookups to fail and results in NaN:
<input v-model="unit[product['unit']]" #change="calculateCost(product['name'])"> ❌
^^^^^^ ^^^^^^
<input v-model="price[product['price']]" #change="calculateCost(product['name'])"> ❌
^^^^^^^ ^^^^^^
<input v-model="unit[product['name']]" #change="calculateCost(product['name'])"> ✅
<input v-model="price[product['name']]" #change="calculateCost(product['name'])"> ✅
Setting the keys to product['name'] ensures the correct lookup for unit and price in calculateCost(). Since the user could enter invalid values (non-numeric strings) or omit a value, it's possible to get NaN, so it would be a good idea to add a NaN-check in calculateCost():
calculateCost(item) {
const unit = Number(this.unit[item]);
const price = Number(this.price[item]);
if (Number.isNaN(unit) || Number.isNaN(price)) return;
this.cost[item] = unit * price;
},
Also, you probably want the cost to react to user input, so switch from #change to #input:
<input v-model="unit[product['name']]" #input="calculateCost(product['name'])">
<input v-model="price[product['name']]" #input="calculateCost(product['name'])">
demo

Setting a Form Value in Vue Js

I am using Struts 1.x in my application. Recently i used Vue js.So, I use the same jsp page for Adding and updating (in this case company). So When i click edit, the details are fetched the page is redirected to that page and form values are set from the action class.
Here is the html portion
<form action="company.do" method="post" name="companyForm">
<html:hidden property="method" value="doAddUpdateCompany" />
<html:hidden property="companyId" value="${companyForm.companyId}" />
<div class="row" >
<div class="col-md-9">
<div class="grid simple">
<div class="grid-title ">
<h4>
<logic:equal value="addCompany" property="method" name="companyForm">
New <span class="semi-bold">Company</span>
</logic:equal>
<logic:equal value="updateCompany" property="method" name="companyForm">
Edit <span class="semi-bold">Company</span>
</logic:equal>
</h4>
<div class="tools"> </div>
</div>
<div class="grid-body">
<table class="tbl_wall" style="width: 100%" >
<tr >
<td class="fi_wall" >Company Name<span class="notify style16"> *</span></td>
<td class="fi_wall" ><html:text property="companyName" name="companyForm" styleClass="med_txt" /></td>
<td> </td>
</tr>
<tr>
<td class="fi_wall" valign="top" >Company Code<span class="notify style16"> *</span> (3 Letter)</td>
<td class="fi_wall" valign="middle" ><html:text property="companyCode" maxlength="3" styleClass="med_txt" name="companyForm" /></td>
<td> </td>
</tr>
<tr id="cmp">
<td class="fi_wall">Company Type </td>
<td class="fi_wall"><select name="companyType" v-model="companyType">
<option value="-1">select</option>
<option v-for=" result in results " v-bind:value="result.commonId">
{{ result.name}}</option>
</select></td>
</tr>
<tr>
<td colspan="3" align="center">
<button type="button" class="btn btn-success" onclick="doSave()" ><i class="fa fa-save"></i> Save</button>
</td>
</tr>
</table> </form>
and the vue Portion
<script type="text/javascript">
new Vue({
el: '#cmp',
data: {
results: [],
companyType : '-1'
},
mounted() {
axios.get('/easyoffice/companyType.do?method=getCompanyTypeAjax').then(response => {
this.results = response.data,
this.companyType = document.forms['companyForm'].companyType.value
})
.catch(e => {
this.errors.push(e)
})
}
});</script>
i used this.companyType = document.forms['companyForm'].companyType.value to set form value but it is not working. Any Thoughts?

How to use extra column in a pivot table

I need to make a custom field just like checklist, but in a table and with a second field "order".
This is what I have:
Model 1: Conditions with relations "belongsToMany"
Model 2: SubServices
These two models are in relations with the table products_service that has the two foreign_keys plus the column "order"
What I can't understand is:
How could save the extra information with backpack.
I know that I can use something like this:
$user->roles()->updateExistingPivot($roleId, $attributes);
but where should I put it?
Here's my code:
class Condition extends Model
{
use CrudTrait;
use Searchable;
public function relService()
{
//dd($this->belongsToMany(SubService::class, 'conditions_service')->withPivot('weight')->withTimestamps());
return $this->belongsToMany(SubService::class, 'conditions_service')->withPivot('weight')->withTimestamps();
}
}
class SubService extends Model
{
use Searchable;
use CrudTrait;
public function conditions()
{
return $this->belongsToMany(Condition::class, 'conditions_service')->withPivot('weight')->withTimestamps();
}
}
Here's my Custom Field Type:
<!-- select2 -->
<div #include('crud::inc.field_wrapper_attributes') >
<label>{!! $field['label'] !!}</label>
#include('crud::inc.field_translatable_icon')
<?php $entity_model = $crud->getModel(); ?>
<div class="row">
<div class="col-sm-12">
<table id="crudTable" class="table table-bordered table-striped display">
<thead>
<tr>
#if ($crud->details_row)
<th></th> <!-- expand/minimize button column -->
#endif
{{-- Table columns --}}
<th>Seleziona</th>
<th>Ordine</th>
{{--<th>Ordine <i class="fa fa-arrow-up" aria-hidden="true"></i></th>
<th>Ordine <i class="fa fa-arrow-down" aria-hidden="true"></i></th>--}}
{{--$tst = $connected_entity_entry->relService->whereIn('id', $connected_entity_entry->id)--}}
</tr>
</thead>
<tbody>
#foreach ($field['model']::all() as $connected_entity_entry) {{--var_dump((empty($connected_entity_entry->conditions->toArray())?"puppa":(empty($connected_entity_entry->conditions->whereIn('id', $connected_entity_entry->id)->toArray())?"puppa uguale":$connected_entity_entry->conditions->whereIn('id', $connected_entity_entry->id)))) --}}
{{-- dump($connected_entity_entry->getPriority($connected_entity_entry->id)) --}}
<tr>
<th scope="row">
<div class="col-sm-4">
<div class="checkbox">
<label>
<input type="checkbox"
name="{{ $field['name'] }}[]"
value="{{ $connected_entity_entry->id }}"
#if( ( old( $field["name"] ) && in_array($connected_entity_entry->id, old( $field["name"])) ) || (isset($field['value']) && in_array($connected_entity_entry->id, $field['value']->pluck('id', 'id')->toArray())))
checked="checked"
#endif > {!! $connected_entity_entry->{$field['attribute']} !!}
</label>
</div>
</div>
</th>
<td>{{--#include('crud::fields.number')--}}
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
{{-- HINT --}}
#if (isset($field['hint']))
<p class="help-block">{!! $field['hint'] !!}</p>
#endif
</div>
</div>
Thank you for your help!
Dave
I found a solution thanks dense-team with his pull request (https://github.com/Laravel-Backpack/CRUD/pull/351)
Here's my code updated:
CrudController:
$this->crud->addField([
'label' => 'Servizi legati',
'type' => 'checklist_ordered',
'name' => 'relService',
'entity' => 'relService',
'attribute' => 'title',
'model' => "App\Models\SubService",
'pivot' => true,
'pivotFields' => [
'weight' => 'Ordinamento',
],
], 'update/create/both');
Here's my Custom Field Type:
<!-- select2 -->
<div #include('crud::inc.field_wrapper_attributes') >
<label>{!! $field['label'] !!}</label>
#include('crud::inc.field_translatable_icon')
#if (isset($field['model']))
<?php $entity_model = $crud->getModel();
$pivot_entries = null;
if (isset($entry)) {
$pivot_entries = $entry->{$field['entity']}->keyBy(function ($item) {
return $item->getKey();
});
}
?>
<div class="row">
<div class="col-sm-12">
<table id="crudTable" class="table table-bordered table-striped display">
<thead>
<tr>
#if ($crud->details_row)
<th></th> <!-- expand/minimize button column -->
#endif
{{-- Table columns --}}
<th>Seleziona</th>
#foreach($field['pivotFields'] as $pivot_chunk)
<th>{{$pivot_chunk}}</th>
#endforeach
</tr>
</thead>
<tbody>
#foreach ($field['model']::all() as $connected_entity_entry)
<tr>
<th scope="row">
<div class="col-sm-4">
<div class="checkbox">
<label>
<input type="checkbox"
name="{{ $field['name'] }}[]"
value="{{ $connected_entity_entry->id }}"
#if( ( old( $field["name"] ) && in_array($connected_entity_entry->id, old( $field["name"])) ) || (isset($field['value']) && in_array($connected_entity_entry->id, $field['value']->pluck('id', 'id')->toArray())))
checked="checked"
#endif > {!! $connected_entity_entry->{$field['attribute']} !!}
</label>
</div>
</div>
</th>
<td>
#foreach(array_chunk($field['pivotFields'], 2, true) as $pivot_chunk)
#foreach ($pivot_chunk as $pivot_field => $pivot_name)
<?php
$pivot_attr = null;
if ($pivot_entries) {
if ($pivot_entries->has($connected_entity_entry->getKey())) {
$pivot = $pivot_entries->get($connected_entity_entry->getKey())->pivot;
$pivot_attr = $pivot->getAttribute($pivot_field);
}
}
?>
<input type="number"
name="{!! $pivot_field !!}[{{ $connected_entity_entry->getKey() }}]"
value="{{ $pivot_attr }}" #include('crud::inc.field_attributes') />
#endforeach
#endforeach
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endif
{{-- HINT --}}
#if (isset($field['hint']))
<p class="help-block">{!! $field['hint'] !!}</p>
#endif
</div>
</div>