Render Input fields based on if field value of the field above/before Vue JS v-for/v-if - vue.js

so I have a simple code of input fields which works as expected, but i try to make it more elegant.
Now my goal is to replace this first code part with a v-for / v-if condition, since i want to render up to 8 fields based on if there is an entry in the field before.
Appreciate any help.
template.js
data () {
return {
company: {
name: null,
brandName: null,
about: null,
avatar: null,
documents: null,
services: [],
serviceInitial: 1,
serviceIndex: 0,
serviceFieldCount: 8,
},}}
template.vue
<form-input
v-if="company.services[0]"
id="website"
v-model="company.services[1]"
class="company-create__input"
name="company.services"
:placeholder="$t('companyCreation.inputServicesPlaceholder') + ' ' + 2"
/>
<form-input
v-if="company.services[1]"
id="website"
v-model="company.services[2]"
class="company-create__input"
name="company.services"
:placeholder="$t('companyCreation.inputServicesPlaceholder') + ' ' + 3"
/>
and so on... up to 8 fields
My new approach which doesn't work yet:
<form-input
v-for="serviceIndex in getServiceFieldCount"
v-if="getServiceInitial + company.services[serviceIndex]>getServiceInitial"
:id="company.services[serviceIndex]"
:key="serviceIndex"
v-model="company.services[serviceIndex]"
class="company-create__input"
name="company.services"
:placeholder="$t('companyCreation.inputServicesPlaceholder')+ ' '+ serviceIndex"
/>

v-for and v-if is not gonna work in same tag , so use a span wrapper around form-input to use the v-for loop and if condition on the form-input tag
<span v-for="serviceIndex in getServiceFieldCount">
<form-input v-if="your condition"/>
</span>

Related

Render html code in Vue.Js without using v-html

I am facing a strange problem.
I use VueTableDynamic as a table library (https://github.com/TheoXiong/vue-table-dynamic)
The whole implementation is correct but there is a small problem... I have certain columns that I want to render with html (for example I want to put a download icon with an href)
this.invoices_params.data.push([
invoice.invoice_number,
invoice.user.company_name ? invoice.user.company_name : invoice.user.first_name + ' ' + invoice.user.last_name,
invoice.total,
(119 / 100) * invoice.total,
invoice.media.length > 0 ?
`<a href=${invoice.media[0].original_url}>Download invoice</a>` :
'No invoice',
moment(invoice.created_at).format('DD-MM-YYYY H:m:s'),
]);
<div class="col-lg" v-if="checkbox_invoices">
{{ trans.invoices.title }}
<vue-table-dynamic :params="invoices_params"></vue-table-dynamic>
</div>
But I can't render that html code and I don't think I can use v-html either
Is there just a way to put that icon there?
I tried to put automatic html code but in vain.
The library allows you to customize the content of a cell using slots: https://github.com/TheoXiong/vue-table-dynamic#slot
Example:
<template>
<vue-table-dynamic :params="params">
<template v-slot:column-5="{ props }">
<a v-if="props.cellData" href=${props.cellData}>Download invoice</a>
<span v-else>No invoice</span>
</template>
</vue-table-dynamic>
</template>
<script>
[...]
this.invoices_params.data.push([
invoice.invoice_number,
invoice.user.company_name ? invoice.user.company_name : invoice.user.first_name + ' ' + invoice.user.last_name,
invoice.total,
(119 / 100) * invoice.total,
invoice.media.length > 0 ? invoice.media[0].original_url : null,
moment(invoice.created_at).format('DD-MM-YYYY H:m:s'),
]);
</script>

PrimeVue DataTable

If I add the :lazy="true" to the as shown below:
<DataTable :value="cars" :lazy="true" :filters="filters" :paginator="true" :rows="10"
:totalRecords="totalRecords" sortMode="multiple" :loading="loading" #page="onPage($event)">
the column filter and sort doesn't work
Example code: https://www.primefaces.org/primevue/#/datatable/filter
How can I make filter and sort work with :lazy as true?
Jobby
You need to configure one rule for each column with data, for example a table of studens ( id , name), and add the json field property name of the associated column in :globalFilterFields.
<Datatable :filters="filters" :globalFilterFields="[ 'id', 'name' ]">
<Column field="id" header="ID"/>
<Column field="name" header="Name"/>
</Datatable>
...
const filters = ref({
global: { value: null, matchMode: FilterMatchMode.CONTAINS},
id: { value: null, matchMode: FilterMatchMode.EQUALS},
name: { value: null, matchMode: FilterMatchMode.CONTAINS},
});
This way you are telling DataTable to filter the column Id and Name, using the defined rules, just remember to use the correct mactchMode to filter numbers, dates or strings, FilterMatchMode.CONTAINS is used with strings.

How to validate multiple user inputs within just one popup using Vue-SweetAlert2

As a coding training, right now I'm making a web page where you can click a "Create" button, which triggers a popup, where you are supposed to fill in 6 data inputs, whose input style varies like text, select etc. (See the code and the attached image below)
<template>
<v-btn class="create-button" color="yellow" #click="alertDisplay">Create</v-btn>
<br/>
<p>Test result of createCustomer: {{ createdCustomer }}</p>
</div>
</template>
<script>
export default {
data() {
return {
createdCustomer: null
}
},
methods: {
alertDisplay() {
const {value: formValues} = await this.$swal.fire({
title: 'Create private customer',
html: '<input id="swal-input1" class="swal2-input" placeholder="Customer Number">' +
'<select id="swal-input2" class="swal2-input"> <option value="fi_FI">fi_FI</option> <option value="sv_SE">sv_SE</option> </select>'
+
'<input id="swal-input3" class="swal2-input" placeholder="regNo">' +
'<input id="swal-input4" class="swal2-input" placeholder="Address">' +
'<input id="swal-input5" class="swal2-input" placeholder="First Name">' +
'<input id="swal-input6" class="swal2-input" placeholder="Last Name">'
,
focusConfirm: false,
preConfirm: () => {
return [
document.getElementById('swal-input1').value,
document.getElementById('swal-input2').value,
document.getElementById('swal-input3').value,
document.getElementById('swal-input4').value,
document.getElementById('swal-input5').value,
document.getElementById('swal-input6').value
]
}
})
if (formValues) {
this.createdCustomer = this.$swal.fire(JSON.stringify(formValues));
console.log(this.createdCustomer);
}
}
}
}
</script>
Technically, it's working. The popup shows up when the "create" button is clicked, and you can fill in all the 6 blanks and click the "OK" button as well. But I want to add some functionalities that check if the user inputs are valid, I mean things like
address should be within 50 characters
firstName should be within 20 characters
customerNumber should include both alphabets and numbers
and so on.
If it were C or Java, I could probably do something like
if(length <= 50){
// proceed
} else {
// warn the user that the string is too long
}
, but when it comes to validating multiple inputs within a single popup using Vue-SweetAlert2, I'm not sure how to do it, and I haven't been able to find any page that explains detailed enough.
If it were just a single input, maybe you could use inputValidor like this
const {value: ipAddress} = await Swal.fire({
title: 'Enter an IP address',
input: 'text',
inputValue: inputValue,
showCancelButton: true,
inputValidator: (value) => {
if (!value) {
return 'You need to write something!'
}
}
})
if (ipAddress) {
Swal.fire(`Your IP address is ${ipAddress}`)
}
, but this example only involves "one input". Plus, what this checks is just "whether an IP address has been given or not" (, which means whether there is a value or not, and it doesn't really check if the length of the IP address is correct and / or whether the input string consists of numbers / alphabets).
On the other hand, what I'm trying to do is to "restrict multiple input values (such as the length of the string etc)" "within a single popup". Any idea how I am supposed to do this?
Unfortunately the HTML tags to restrict inputs (e.g. required, pattern, etc.) do not work (see this issues),
so I find two work around.
Using preConfirm as in the linked issues
You could use preConfirm and if/else statement with Regex to check your requirement, if they are not satisfied you could use Swal.showValidationMessage(error).
const{value:formValue} = await Swal.fire({
title: "Some multiple input",
html:
<input id="swal-input1" class="swal-input1" placeholder="name"> +
<input id="swal-input2" class="swal-input2" placeholder="phone">,
preConfirm: () => {
if($("#swal-input1").val() !== "Joe"){
Swal.showValidationMessage("your name must be Joe");
} else if (!('[0-9]+'.test($("#swal-input2").val())){
Swal.showValidationMessage("your phone must contain some numbers");
}
}
});
Using Bootstrap
In this way Bootstrap does the check at the validation, you need to include class="form-control" in your input class and change a little your html code.
If some conditions fails, the browser shows a validation message for each fields, in the order they are in the html code.
const {value: formValue} = await Swal.fire({
title: 'Some multiple inputs',
html:
'<form id="multiple-inputs">' +
'<div class="form-group">' +
'<input type="text" class="form-control swal-input1" id="swal-input1" min=2 max=4 required>' +
'</div>' +
'<div class="form-group">' +
'<input type="text" class="form-control swal-input2" id="swal-input2" placeholder="Name" pattern="[A-Za-z]" required>' +
'</div>' +
'</form>',
});
I have tried both the solution, actually only with Bootstrap3 but it should work also with the latest release.

Angular5 data prepopulation one way binding not happening

I am using a parent component travelerInput that creates travelerListForm using model in my component and iterate it extracting travelerForm which is then passed to the nested child components using #Input:
for (let i = 1; i <= numberOfTravelers; i++) {
const tId = `${ptc}_0${i}`;
const Id = `${TravelerInput.pIndex++}`;
const traveler = new Traveler({passengerTypeCode: ptc, id: Id, tid: tId, names: [new Identity({
firstName: "",
middleName: "",
lastName: "",
title: "",
nameType: "native",
isDisplayed: false
})],
dateOfBirth: undefined ,
gender: "unknown",
accompanyingTravelerId: "",
accompanyingTravelerTid: ""
});
travelerList.push(traveler);
}
HTML
<div class="alpi-section col-xs-12 col-sm-12 col-md-12 col-lg-12"
*ngFor="let travelerForm of travelerListForm.controls; let tIndex = index;">
<o3r-simple-traveler-input
[config]="config.simpleTravelerInput"
[travelerForm]="travelerForm"
[index]="tIndex">
</o3r-simple-traveler-input>
Now we have a drop down in parent component with a list of travelers. The selected passenger in the drop down will have its information prepopulated in the form fields which are nested child components. I am using travelerForm which is iterated over travelerListForm in child components as #Input. On change of drop down I am binding the value of the passenger information to the corresponding index of travelerListForm which is also getting updated but on UI there is no update.
pickSelectedADTPassenger(adult:any, index: number){
this.selectedADTId= this.ADTTravelerId[adult];
this.travelerListForm.controls[index].value.names[0].firstName = this.selectedADTId.IDENTITY_INFORMATION.FIRST_NAME; //ASSISGNMENT
}
Have also tried using ngModel in the child component input field where I want the value to be prepopulated but it did not work:
<input type="text"
[(ngModel)]="travelerForm.controls.firstName.value"
class="form-control"
placeholder="FIRST NAME"
maxlength="52"
formControlName="firstName">
</div>
Please suggest.

Vue.js method returning undefined when accessing data

I'm using Vue.js to populate a list of locations, and using a method that should return a formatted map link using the address.
The problem is that in the method, trying to return this.Address ends up in undefined. Here's what I've got:
// the Vue model
pbrplApp = new Vue({
el: '#pbrpl-locations',
data: {
'success' : 0,
'errorResponse' : '',
'wsdlLastResponse' : '',
't' : 0,
'familyId' : 0,
'brandId' : 0,
'srchRadius' : 0,
'lat' : 0,
'lon' : 0,
'response' : []
},
methods: {
getDirections: function(address,city,st,zip){
// THIS Doesn't work:
//var addr = this.Address + ',' + this.City + ',' + this.State + ' ' + this.Zip;
var addr = address + ',' + city + ',' + st + ' ' + zip;
addr = addr.replace(/ /g, '+');
return 'https://maps.google.com/maps?daddr=' + addr;
}
}
});
// the template
<ul class="pbrpl-locations">
<template v-for="(location,idx) in response">
<li class="pbrpl-location" :data-lat="location.Latitude" :data-lon="location.Longitude" :data-premise="location.PremiseType" :data-acct="location.RetailAccountNum">
<div class="pbrpl-loc-idx">{{idx+1}}</div>
<div class="pbrpl-loc-loc">
<div class="pbrpl-loc-name">{{location.Name}}</div>
<div class="pbrpl-loc-address">
<a :href="getDirections(location.Address,location.City,location.State,location.Zip)" target="_blank">
{{location.Address}}<br>
{{location.City}}, {{location.State}} {{location.Zip}}
</a>
</div>
</div>
</li>
</template>
</ul>
Right now, I'm having to pass the address, city, state and zip code back to the model's method, which I know is wrong - but I can't find anything in the vue.js docs on the proper way to get the values.
What's the proper way to get the method to reference "this" properly? Thanks for your help.
this.Address doesn't work because Address is not part of your data. It looks like what you are doing is iterating through response, which somehow gets populated with locations.
You could just pass location to getDirections instead of each of the parameters.
getDirections(location){
let addr = location.Address+ ',' + location.City + ',' + location.State + ' ' + location.Zip
....
}
And change your template to
<a :href="getDirections(location)" target="_blank">
In general, in Vue methods, this will refer to the Vue itself, which means that any property that is defined on the Vue (of which properties defined in data are included) will be accessible through this (barring there being a callback inside the method that incorrectly captures this). In your case, you could refer to any of success, errorResponse, wsdlLastResponse, t, familyId, brandId, srchRadius, lat, lon, or response through this in getDirections.