Populate data onto select tag(multiple) with data 'selected' - laravel-5.7

I'm making a project management system with Laravel 5.7 where I have my tables User, Project, Project User and Task(not important here). I'm having difficulties
trying to edit my Project data as each Project has many User(collaborator). My Project User table acts as a pivot table to store the many to many relationship. All of the project Edit will be displayed in a bootstrap modal in a single page which i used a foreach loop to display all the data. So my problem now is I'm trying to load my data onto my multiple select tag while selecting the options that found.
Example User table has
James
Dexter
In project "A" the collaborator is
James
When i edit Project "A" the select input tag would set James with the selected attribute while Dexter would be "unselected". I have managed to populate the User name and set the selected attributes but due to some logically error, if I edit Project "A", it would set both James and Dexter as selected.
These are my tables
User
u_id PK
name
Project
p_id PK
p_name
status (Active/Inactive)
type (Team/Personal)
Project User
pu_id PK
p_id FK of Project table
u_id FK of user table
Project Controller(Index)
//Get Team data based on project type and user id
$teamProject = DB::table('projects_users')
->join('projects','projects_users.p_id','=','projects.p_id')
->select('projects_users.*','projects.*')
->where('projects.type','=','Team')
->where('projects.status','=','Active')
->where('u_id','=',Auth::user()->u_id)
->get();
//Get all collaborator
$allProjUser = DB::table('projects_users')
->join('projects','projects_users.p_id','=','projects.p_id')
->select('projects_users.*','projects.*')
->where('projects.type','=','Team')
->where('projects.status','=','Active')
->where('projects_users.role','=','Colab')
->get()->keyBy('u_id');
$allUser = User::where('u_id', '!=', Auth::id())->get();
Blade View
#foreach ($teamProject as $proj)
{!!Form::open(['action' => ['ProjectController#update',$proj->p_id],'method' => 'POST'])!!}
<!--Title-->
<div class="form-group row">
<label for="inputEmail3" class="col-md-3 col-form-label">Project Title</label>
<div class="col-sm-8">
<input type="title" class="form-control" id="p_name" name="p_name" placeholder="Title"
value="{{$proj->p_name}}" required>
</div>
</div>
<!--Colaborator-->
<div class="form-group row">
<label for="inputEmail3" class="col-md-3 col-form-label">Collaborator</label>
<div class="col-sm-6">
<select name="colab[]" id="colabEdit-{{$proj->p_id}}" placeholder="Select Your Member" required multiple>
<option value="" disabled>Select Your Member</option>
#foreach ($allUser as $user)
//Should validate if user exists in the project pivot table here
#if ($allProjUser->has($user->u_id))
<option value="{{ $user->u_id }}" selected>{{ $user->name }}</option>
#else
<option value="{{ $user->u_id }}">{{ $user->name }}</option>
#endif
#endforeach
</select>
</div>
</div>
#endforeach
Any help would be appreciated and sorry if my sentence structure or english is unclear. Thank you

Would it work to pass your "selected" values in via the controller vs. trying to apply the logic in the view?
Making some assumptions about your project.
In your controllers 'edit' method...
$users = User::all();
$project = Project::findOrFail($id);
foreach ($project->user as $projectUser) {
$selectedTags[] = $projectUser->id;
}
return view('edit', compact('project', 'users', 'selectedTags');
Then in your view...
<select multiple name="collaborators[]">
#foreach ($users as $user)
#if (in_array($user->id, $selectedTags))
<option selected value="{{$user->id}}">{{$user->name}}</option>
#else
<option value="{{$user->id}}">{{$user->name}}</option>
#endif
#endforeach
</select>
Then in the 'store' method, delete from project_user where p_id = the ID of the project edited. Add a new record for each of the collaborators[] array.

Related

How can I make dropdown list with freemarker?

I am trying to get a list from datatbase using Freemarker. I want to make select dropdown list, but I don't undestand what I missed.
I did this:
<div class="form-group">
<select name="category" class="form-control" required>
<#list categories! as category>
<option value="${category.id}">${category.name}</option>
</#list>
</select>
</div>
I have a form but I don't see any options.
With Thymeleaf I could do this but in the project I want to use freemarker
<div class="form-group">
<select th:field="*{category}" class="form-control" required>
<th:block th:each="category : ${categories}">
<option th:text="${category.name}" value="${category.id}"/>
</th:block>
</select>
</div>
In fact I need "translate" this part from Thymeleaf to Freemarker and I don't know how.
Yes, the code fragement was correct, I just placed in a PostMapping instead of GetMapping. Now it works good with controller below:
#GetMapping("/items")
public String main(Model model) {
Iterable<Item> items;
model.addAttribute("items", items);
List<Category> categories = categoryRepository.findAll();
model.addAttribute("categories", categories);
return "items";
}

Vue v-for loop bind object key to select element

I have data like this - the keys for the phone object can be "mobile", "home"...
contacts[
11:{
name: "Mr Blobby"
phone: {
mobile: "07123 456789",
home: "0201 2345 6789"
}
...
}
...{}
Displaying it (cRud) is easy:
<div v-for="contact in contacts" :key="contact.id" :contact="contact">
<div v-for="(phone, type) in contact.phone" :key="type" :phone="phone">
<b>{{ type }}</b>
<h2>{{ phone }}</h2>
</div>
</div>
But how do I bind specifically the key (mobile/home...) using a select and v-model (CrUd) ?
<div v-for="(phone, index) in contact.phone" :key="phone">
<input type="tel" v-model.trim="contact.phone[index]" />
<select v-model="???">
<option value="mobile">Mobile</option>
option value="home">Home</option>
</select>
</div>
The code below should work if you want to iterate through the properties of the phone object. You can then bind the select value to a variable with v-model.
<select v-model="selectedPhone">
<option disabled value="">Select a phone</option>
<option
v-for="(value, name) in contact.phone"
:key="value"
:value="name"
>
{{ name }}
</option>
</select>
in v-for we provide the second argument 'name'(a.k.a. key) which will be 'mobile' or 'home' and then we set it as the options values.
So we set the phone object keys as the options values which i think is what you're aiming for?
You should also declare the initial value of the v-model variable inside the data option of your component.
data () {
return {
selectedPhone: ''
}
}

Split data from database column & view as string using Laravel

I have inserted multiple string in a column as an array in my database. They are separated by coma(,).
In the view page for route no 1 there are 3 stoppage points. Now I want to show them separately into different input fields. But they are shown into same filed as an array. So what should I do...?
<div class="col-md-4">
<div class="group">
<label>Stoppage Point</label>
<input type="text" value="{{ $allroute->stoppagePoint }}" name="stoppagePoint" class="input1 removeDis {{ $errors->has('stoppagePoint') ? ' is-invalid' : '' }}" disabled required>
#if ($errors->has('stoppagePoint'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('totalStoppage') }}</strong>
</span>
#endif
</div>
</div>
Do you want to execute it inside the blade template or do the logic in the controller
But i think the best way is to use the controller
You can use explode php function
$stoppages = explode(',',$points->stoppagePoints);
then this creates an array then you can append it to the view
#foreach (explode(',', $allroute->stoppagePoint) as $stoppagePoint)
<input type="text" value="{{ trim($stoppagePoint) }}" ...
#endforeach

how to define a select component within a clr-tab

Tried to insert a "select" component under a tab. Basically, the tab just displays some dynamic forms. The select is a list of string for user selection Looks like my definition is correct. Do not know why it messed up the whole angular/clarity UI page.
<clr-tab>
<button clrTabLink>Submission Form</button>
<clr-tab-content>
<br>
<label class="required" for="uniqueCertIDs">Unique Cert IDs</label>
<div class="select">
<select id="partnercertIDs" formControlName="EEPortalProductDetails">
<option *ngFor="let ucertID of uniquecertIDs" [value]="ucertID.UniqueCertId">{{ucertID.UniqueCertId}} </option>
</select>
</div>
Very likely, the scope of the select portion is not correct. Failed finding related documentation.
It's difficult to say whats happening without a running example.
I created a simple form with a select in a tab and it seems to be ok.
Here is the template code for my tabs:
<clr-tabs>
<clr-tab>
<button clrTabLink id="link1">Tab1</button>
<clr-tab-content id="content1" *clrIfActive>
<h3>Form 1</h3>
<form>
<div class="form-group">
<label for="selects_1">This is a select box</label>
<div class="select">
<select id="selects_1">
<option>Select</option>
<option *ngFor="let user of users" [value]="user">{{user}} </option>
</select>
</div>
</div>
</form>
</clr-tab-content>
</clr-tab>
</clr-tabs>
You can see this running here: https://stackblitz.com/edit/so-tabs-form-select
If this doesn't solve your issue, can you fork the StackBlitz and recreate it there?
<form [formGroup]="partnersForm" >
<div class="form-group">
<label class="required" for="selects_1">Unique Cert IDs</label>
<div class="select" >
<select id="selects_1" formControlName="partnerFormCertIDs" ng-change="selectAction()">
<option *ngFor="let ucertID of uniquecertIDs" [value]="ucertID.UniqueCertId" >{{ucertID.UniqueCertId}}</option>
</select>
</div>
</div>
</form>
and in my Session.ts file. Debug using console, the alert never shows up
selectAction() {
alert("selected value changed !!!!");
}
#nextgen-ui Regarding your second issue, the data binding syntax should be either on-change or (change); ng-change is an AngularJS directive.
Please see this Stackblitz.
#Jose Gomes
The event is defined as updateCertData()
<form [formGroup]="partnersForm" >
<div class="form-group">
<label class="required" for="selects_1">Unique Cert IDs</label>
<div class="select">
<select id="selects_1" formControlName="partnerFormCertIDs" (change)="updateCertData()">
<option *ngFor="let ucertID of uniquecertIDs" [value]="ucertID.UniqueCertId">{{ucertID.UniqueCertId}}</option>
</select>
</div>
</div>
</form>
And I defined a POST API in the event
updateCertData(){
let selectedCertID = this.partnersForm.get('partnerFormCertIDs').value;
for ( let partnerInfo of this.uniquecertIDs) {
if(partnerInfo.UniqueCertId == selectedCertID){
this.extractSubmit(this.cert);
this.submit[0].Option[0].value = partnerInfo.ProductId;
this.submit[0].Option[1].value = partnerInfo.ProductName;
this.certsService.setSubmissionProduct(this.certId, this.submit);
break;
}
}
}
this.certsService.setSubmissionProduct is a POST API, sending data back to UI Server
setSubmissionProduct(sessionId: string, info:any){
let body = {'submitConfig': info};
let url = GLOBALS.baseUrl + "session/" + sessionId + "/submitproduct";
return this.post(url, body);
}
The this.post never sends message to the controller successfully. I tried several other post methods, which works well in other logic part, but never sends message successfully if it is put within this "change" event.

meteor onRendered not called

I’m trying to have a reactive bootstrap selectpicker but I have a weird behaviour:
An event has to change the options of the select but it works only after the first event which is not working because the app doesn’t go into the onRendered part…
This is the onRendered part:
var renderTimeout = false;
Template.printerselect.onRendered( function(){
if (renderTimeout !== false) {
Meteor.clearTimeout(renderTimeout);
}
renderTimeout = Meteor.setTimeout(function() {
$('#printerName').selectpicker("refresh");
renderTimeout = false;
}, 10);
});
Template.printerSetupForm.onRendered( function(){
$('.selectpicker').selectpicker();
});
here, the templates :
<div class="col-lg-3 col-md-4 col-xs-12 form-group">
<label>COMPANY</label>
<select id="printerCompany" class="form-control selectpicker" name="printer[company]">
<option selected="true" disabled="disabled" value={{company}}>
Please Select A Printer Company
</option>
{{#each Companies}}
<option value="{{company}}" {{printerCompanySelected company}}> {{company}}</option>
{{/each}}
</select>
</div>
<div class="col-lg-3 col-md-4 col-xs-12 form-group">
<label>PRINTER NAME</label>
<select id="printerName" class="form-control selectpicker" name="printer[name]">
<option selected="true" disabled="disabled" value={{name}}>
Please Select A Printer
</option>
{{#each Names}}
<!--<option value="{{name}}" {{printerNameSelected name}}>
{{name}}
</option>-->
{{>printerselect}}
{{/each}}
</select>
</div>
<template name="printerselect">
<option value="{{name}}"> {{name}} </option>
</template>
The refresh is called when the page is rendered.
Then I change the company which changes some Session variables and reactively to change the name select options but the refresh is not called so that doesn’t come to the onrendered part.
But when I change again the company it’s working, the onRendered part is called.
Weird thing is that even if this is not displaying the right names, when i’m choosing a name which doesn’t match with the company, the select chooses the right one.
Sorry for my english in advance, I did my best.
Thanks you in advance !
EDIT: Names helper :
Names: () => {
company=Session.get('printer').company;
if(typeof company!='undefined') {
return Printers.find({company: company}).fetch();
} else {
return Printers.find().fetch();
}
}
I set the Session variable 'printers' with an empty field. When I select a company, it's now working but without company, I don't get any printers because I don't have to test company with 'undefined' but with empty field.
So I changed to test with empty field and it isn't working anymore...
So weird that a test could cancel a onRendered, this must be an issue with the Mongo stuff.
I will continue to search on it.

Resources