How to inject dynamic Vue 3 html code into SetContent - leaflet

I'm pretty new to Vue 3 and trying to use leaflet to display a map of markers. In my html code of my main map component, I have some home made controls under the map that I'm using to filter the markers:
<div class='range-slider'>
<input type="number" min="0" max="300" step="1" v-model="sliderMin"> units to
<input type="number" min="0" max="300" step="1" v-model="sliderMax"> units
<input type="range" min="0" max="300" step="10" v-model="sliderMin">
<input type="range" min="0" max="300" step="10" v-model="sliderMax">
</div>
with slidermin/slidermax being computed properties:
computed: {
sliderMin: {
get: function() {
var val = parseInt(this.ValueMin);
this.updateDataPolygon(this.map);
return val;
},
set: function(val) {
val = parseInt(val);
if (val > this.ValueMax) {
this.ValueMax = val;
}
this.ValueMin = val;
}
},
sliderMax: {
get: function() {
var val = parseInt(this.ValueMax);
this.updateDataPolygon(this.map);
return val;
},
set: function(val) {
val = parseInt(val);
if (val < this.ValueMin) {
this.ValueMin = val;
}
this.ValueMax = val;
}
},
}
I'd like to move those controls to a sidebar of my map and the sidebar component expects its content to be inserted using SetContent method:
var sidebar = L.control.sidebar('sidebar', {
position: 'left'
});
sidebar.setContent('<div class="range-slider">Surface du logement : '+
'<input type="number" min="0" max="300" step="1" v-model="sliderMin"> units to '+
'<input type="number" min="0" max="300" step="1" v-model="sliderMax"> units'+
'<input type="number" min="0" max="300" step="1" v-model="sliderMin">'+
'<input type="number" min="0" max="300" step="1" v-model="sliderMax">'+
'<input type="range" min="0" max="300" step="10" v-model="sliderMin"><input type="range" min="0" max="300" step="10" v-model="sliderMax">'+
'</div>');
map.addControl(sidebar);
When I try that, the html is displayed in the sidebar but my controls are not dynamic anymore.
Do you know how I can make them reactive again with Vue3?
Thanks a lot!
Alex

Related

Why am I getting "500 (Internal Server Error)" and "Uncaught (in promise) SyntaxError: Unexpected token < "?

I am trying to insert some data into the database through a fetch API POST request to a Next.js API route but I am getting the following two error messages in the browser's console:
api/addCompany/addCompany:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) register:1
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
These are my project's folders (it's relevant because of Next.js's routing system)
This is the component where I am doing the fetch API request (please don't judge my poor Typescript skills, I am new to it, still not finding the propper event type):
import styles from '../styles/Register.module.css'
import { NextPage } from "next"
import { prisma } from '../prisma/prisma_client';
import { Prisma } from '#prisma/client';
import { useSession } from "next-auth/react"
const Register: NextPage = () => {
const createCompany: any = async (event: any) => {
event.preventDefault()
const company: Prisma.CompanyCreateInput = {
companyName: event.target.companyName.value,
gender: event.target.gender.value,
firstName: event.target.firstName.value,
lastName: event.target.lastName.value,
street: event.target.street.value,
houseNumber: parseInt(event.target.houseNumber.value),
postcode: parseInt(event.target.postcode.value),
city: event.target.city.value,
country: event.target.country.value,
countryCode: event.target.countryCode.value,
callNumber: parseInt(event.target.callNumber.value),
emailAddress: event.target.emailAddress.value,
website: event.target.website.value,
socials: {},
companyUser: {
connect: { id: 'cl0y4y8xo0021mwtcmwlqfif6' }
}
}
const companyJSON = JSON.stringify(company)
const endpoint = '/api/addCompany/addCompany'
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: companyJSON,
}
const response = await fetch(endpoint, options)
const data = await response.json()
console.log(data)
}
return (
<form onSubmit={createCompany} className={styles.form} id="signupForm" noValidate>
<h2>Company Information</h2>
<div className="fieldWrapper">
<input type="text" id="companyName" name="companyName" placeholder=" " />
<label htmlFor="companyName">Company Name<span>*</span></label>
<div className='errorMessage'></div>
</div>
<div className="fieldWrapper">
<input type="text" list="genders" id="gender" name="gender" placeholder=" " />
<label htmlFor="gender">Gender<span>*</span></label>
<div className='errorMessage'></div>
<datalist id="genders">
<option>Female</option>
<option>Male</option>
</datalist>
</div>
<div className="fieldWrapper">
<input type="text" id="firstName" name="firstName" placeholder=" " />
<label htmlFor="firstName">First Name<span>*</span></label>
<div className='errorMessage'></div>
</div>
<div className="fieldWrapper">
<input type="text" id="lastName" name="lastName" placeholder=" " />
<label htmlFor="lastName">Last Name<span>*</span></label>
<div className='errorMessage'></div>
</div>
<div className="fieldWrapper">
<input type="text" id="street" name="street" placeholder=" " />
<label htmlFor="street">Street<span>*</span></label>
<div className='errorMessage'></div>
</div>
<div className="fieldWrapper">
<input type="number" id="houseNumber" name="houseNumber" placeholder=" " />
<label htmlFor="houseNumber">House Number<span>*</span></label>
<div className='errorMessage'></div>
</div>
<div className="fieldWrapper">
<input type="number" id="postcode" name="postcode" placeholder=" " />
<label htmlFor="postcode">Postcode<span>*</span></label>
<div className='errorMessage'></div>
</div>
<div className="fieldWrapper">
<input type="text" id="city" name="city" placeholder=" " />
<label htmlFor="city">City<span>*</span></label>
<div className='errorMessage'></div>
</div>
<div className="fieldWrapper">
<input type="text" id="country" name="country" placeholder=" " />
<label htmlFor="country">Country<span>*</span></label>
<div className='errorMessage'></div>
</div>
<div className="fieldWrapper">
<input type="text" id="countryCode" name="countryCode" placeholder=" " />
<label htmlFor="countryCode">Country Code<span>*</span></label>
<div className='errorMessage'></div>
</div>
<div className="fieldWrapper">
<input type="number" id="callNumber" name="callNumber" placeholder=" " />
<label htmlFor="callNumber">Call Number<span>*</span></label>
<div className='errorMessage'></div>
</div>
<div className="fieldWrapper">
<input type="email" id="emailAddress" name="emailAddress" placeholder=" " />
<label htmlFor="emailAddress">Email Address<span>*</span></label>
<div className='errorMessage'></div>
</div>
<div className="fieldWrapper">
<input type="text" id="website" name="website" placeholder=" " />
<label htmlFor="website">Website</label>
</div>
<div className="fieldWrapper">
<input type="text" id="socials" name="socials" placeholder=" " />
<label htmlFor="socials">Socials</label>
</div>
<div className="fieldWrapper">
<button type="submit">Save</button>
</div>
</form>
)
}
export default Register
And this is the the addCompany file's code which serves as the Next.js API route for my fetch API request:
import { Prisma } from '#prisma/client';
import { NextApiRequest, NextApiResponse } from 'next';
import { prisma } from '../../../prisma/prisma_client';
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const {body} = req;
const companyData: Prisma.CompanyCreateInput = JSON.parse(body);
const addCompany = await prisma.company.create({
data: companyData
})
res.status(200).json(addCompany);
}
export default handler
I appreciate any help. Thank you.
I tried to comment out
const data = await response.json() console.log(data)
in the Register component so the error "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" disappeared but that is no solution to the problem at all.
I also tried to adjust the route of my fetch request to any possible option because I wasn't sure how exactly Next.js autocompletes it, for example I tried: '/api/addCompany/addCompany.ts' and so on.
I expect the problem to be something small, I hope it isn't typo.
Thank you again.
PS: I also checked similar posts on this matter but couldn't find a fix for my problem.
There is no need to reparse the body data in the API endpoint because Next.js middleware convert that data to an object already:
API routes provide built in middlewares which parse the incoming
request (req). Those middlewares are:
req.cookies - An object containing the cookies sent by the request. Defaults to {}
req.query - An object containing the query string. Defaults to {}
req.body - An object containing the body parsed by content-type, or null if no body was sent
something like below should work:
import { Prisma } from '#prisma/client';
import { NextApiRequest, NextApiResponse } from 'next';
import { prisma } from '../../../prisma/prisma_client';
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const {body: companyData} = req;
//const companyData: Prisma.CompanyCreateInput = JSON.parse(body);<- No need to reparse the data here
const addCompany = await prisma.company.create({
data: companyData
})
res.status(200).json(addCompany);
}
export default handler
Thanks to this answer here for clarification.

Can't type in HTML form text/password/number input field (website with Unity WebGL build)

We are developing a site using Angular 9.
We have also integrated a Unity3D WebGL build in it.
When I try to type something in a text/password/number input field inside one of my forms, it doesn't write anything and the field doesn't seem to receive the input; also, the variable I bound the field to is not updated with the new value.
What makes it weirder is that:
I can select the input field (it gets highlighted as if I can start typing)
I can do CTRL+C on the field and what I copied somewhere else is pasted, as expected
I can use the type="number" arrow selectors to set the value of the field
I cannot type from the keyboard in the fields
I can interact as expected with other form tags, such as <select>
If I reload the page, it usually starts working as expected and I can type into the fields
Here is the code from my login form (component.ts above, template HTML below)
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../auth.service'
import { first } from 'rxjs/operators';
import { Router, ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
email: string = "";
password: string = "";
returnUrl: string = "home";
constructor(private router: Router, private route: ActivatedRoute, private authService: AuthService) { }
ngOnInit(): void {
let tmpReturnUrl = this.route.snapshot.queryParams["returnUrl"];
if (tmpReturnUrl != undefined)
{
console.log("true");
this.returnUrl = tmpReturnUrl;
}
else
console.log("false");
setInterval(() => {
console.log("EMAIL: " + this.email);
}, 1000);
}
onSubmit(){
this.authService.login(this.email, this.password)
.pipe(first())
.subscribe(
result => {
console.log("CAIOAOAOAOOA");
this.router.navigate([this.returnUrl]);
},
err => console.log(err)
);
}
}
<div class="card z-depth-5 w-50">
<div class="card-body">
<div class="card-title">Log in</div>
<div class="card-text">
<form #companyLoginForm="ngForm" (ngSubmit)="onSubmit()">
<mat-form-field>
<mat-label>Email: </mat-label>
<input matInput required type="text" name="email" id="email" [(ngModel)]="email">
</mat-form-field>
<mat-form-field>
<mat-label>Password: </mat-label>
<input matInput required type="password" name="password" id="password" [(ngModel)]="password">
</mat-form-field>
<button type="submit" [disabled]="!companyLoginForm.form.valid">Login</button>
</form>
<a routerLink="/company-register">
<button mdbBtn type="button" color="primary" class="relative waves-light">Sign Up</button>
</a>
</div>
</div>
</div>
And here, the code from another form where I also use type="number" and <select> (component.ts above, template HTML below)
import { Component, OnInit, Output } from '#angular/core';
import { BlockFormService } from '../block-form.service';
import { BlockData } from '../blockCardData';
import { BlockUtilsService } from '../block-utils.service';
import { ApiService } from '../../core/api.service'
import { NgForm } from '#angular/forms';
#Component({
selector: 'app-block-form',
templateUrl: './block-form.component.html',
styleUrls: ['./block-form.component.less']
})
export class BlockFormComponent implements OnInit {
updateComplete : Boolean = false;
materials : string[];
products : string[];
varieties : string[];
nations : string[];
// companies : {name: string, id: string}[] = [];
company : string = "";
colors : string[] = ["White", "Grey", "Black", "Brown", "Red", "Green", "Yellow", "Blue"];
blockData : BlockData = {_id : "", blockId: "", company: "", material: "", product: "",
variety: "", color: "", nation: "", modelName : "", imagePreview : "",
price: null, blockNumber: "",
length: null, height: null, width: null,
weight: null
};
imagePreview: File = null;
zipFile: File = null;
invalidUpload: boolean = false;
constructor( private blockFormService: BlockFormService, public blockUtils: BlockUtilsService, private companiesUtils: ApiService )
{ }
ngOnInit(): void {
this.materials = this.blockUtils.getMaterials();
this.colors = this.blockUtils.getColors();
this.companiesUtils.getLoggedCompany().subscribe(companiesResult => {
this.blockData.company = companiesResult._id;
this.company = companiesResult.name;
});
}
onImageSelected(event){
console.log(event.target.files[0]);
if (event.target.files[0].type === "image/png")
{
if (this.invalidUpload)
this.invalidUpload = false;
this.imagePreview = event.target.files[0];
}
else{
if (!this.invalidUpload)
this.invalidUpload = true;
event.target.value = null;
}
}
onMaterialSet(newMaterial): void{
console.log("Material set");
this.products = this.blockUtils.getProducts(newMaterial);
//console.log(this.products);
// if (this.products.length > 0)
// this.blockData.product = this.products[0];
// else
this.blockData.product = "";
this.onProductSet(this.blockData.product);
}
onProductSet(newProduct): void{
console.log("Product set");
this.varieties = this.blockUtils.getVarieties(this.blockData.material, newProduct);
// if (this.varieties.length > 0)
// this.blockData.variety = this.varieties[0];
// else
this.blockData.variety = "";
this.nations = this.blockUtils.getNations(this.blockData.material, this.blockData.product);
if (this.nations.length > 0)
this.blockData.nation = this.nations[0];
else
this.blockData.nation = "";
this.onVarietySet(this.blockData.variety);
}
onVarietySet(newVariety): void{
console.log("Variety set");
// this.nations = this.blockUtils.getNations(this.blockData.material, this.blockData.product);
// if (this.nations.length > 0)
// this.blockData.nation = this.nations[0];
// else
// this.blockData.nation = "";
}
onSubmit(blockForm : NgForm, imageField, zipField): void{
this.blockFormService.sendBlock(this.blockData, this.imagePreview, this.zipFile)
.subscribe(res => {
console.log("Sent!");
this.updateComplete = true;
});
this.blockData = {
_id: "", blockId: "", company: "", material: "", product: "",
variety: "", color: "", nation: "", modelName: "", imagePreview: "",
price: null, blockNumber: "",
length: null, height: null, width: null,
weight: null
};
blockForm.resetForm();
imageField.value = null;
zipField.value = null;
this.imagePreview = null;
this.zipFile = null;
}
}
<div class="form-group">
<div class="text-center" *ngIf='updateComplete'>
Block added successfuly
</div>
<form #blockForm="ngForm" (ngSubmit)="onSubmit(blockForm, imageField, zipField)">
<div class="container">
<div class="row">
<div class="col-3">
<mat-form-field>
<mat-label>Company: </mat-label>
<!-- <mat-select required [(ngModel)]="blockData.company" name="company-field"
id="company-field">
<mat-option selected [value]="company.id">{{company.name}}</mat-option>
</mat-select> -->
<input matInput disabled [value]="company" type="text" name="company-field" id="company-field">
</mat-form-field>
</div>
<div class="col-3">
<mat-form-field>
<mat-label>Material: </mat-label>
<mat-select #matField required [(ngModel)]="blockData.material" name="kind-field"
id="kind-field" (selectionChange)="onMaterialSet(blockData.material)">
<mat-option *ngFor="let mat of materials" [value]="mat">{{mat}}</mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="col-3">
<mat-form-field>
<mat-label>Product: </mat-label>
<mat-select required [(ngModel)]="blockData.product" name="product-field"
id="product-field" (selectionChange)="onProductSet(blockData.product)">
<mat-option *ngFor="let prod of products" [value]="prod">{{prod}}</mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="col-3">
<mat-form-field>
<mat-label>Block Number: </mat-label>
<input matInput required [(ngModel)]="blockData.blockNumber" type="text" name="blockNumber-field" id="blockNumber-field">
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col-3">
<mat-form-field>
<mat-label>Variety: </mat-label>
<mat-select required [(ngModel)]="blockData.variety" name="variety-field" id="variety-field"
placeholder="Variety" (selectionChange)="onVarietySet(blockData.variety)">
<mat-option *ngFor="let variety of varieties" [value]="variety">{{variety}}</mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="col-3">
<!-- <label for="color-field">Color: </label> -->
<mat-form-field>
<mat-label>Color: </mat-label>
<mat-select required [(ngModel)]="blockData.color" name="color-field" id="color-field" placeholder="Color">
<mat-option *ngFor="let col of colors" [value]="col">{{col}}</mat-option>
</mat-select>
</mat-form-field>
<!-- <input #colField required [(ngModel)]="blockData.color" type="text" name="color-field" id="color-field" placeholder="Color"> -->
<!-- <color-circle #colorField [colors]='["#f44336", "#e91e63", "#9c27b0", "#673ab7", "#3f51b5", "#2196f3", "#03a9f4", "#00bcd4", "#009688", "#4caf50", "#8bc34a", "#cddc39", "#ffeb3b", "#ffc107", "#ff9800", "#ff5722", "#795548", "#607d8b"]' name="color-field" id="color-field" (onChange)="blockData.color = $event.color.hex"></color-circle> -->
</div>
<div class="col-3">
<mat-form-field>
<mat-label>Nation: </mat-label>
<!-- <mat-select required [(ngModel)]="blockData.nation" name="nation-field"
id="nation-field">
<mat-option *ngFor="let nat of nations" [value]="nat">{{nat}}</mat-option>
</mat-select> -->
<input matInput disabled [(ngModel)]="blockData.nation" type="text" name="nation-field" id="nation-field">
</mat-form-field>
</div>
<div class="col-3">
<mat-form-field>
<mat-label>Price: </mat-label>
<input matInput required [(ngModel)]="blockData.price" type="number" name="price-field" id="price-field">
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col-3">
<mat-form-field>
<mat-label>Length: </mat-label>
<input matInput required [(ngModel)]="blockData.length" type="number" name="length-field" id="length-field">
</mat-form-field>
</div>
<div class="col-3">
<mat-form-field>
<mat-label>Width: </mat-label>
<input matInput required [(ngModel)]="blockData.width" type="number" name="width-field" id="width-field">
</mat-form-field>
</div>
<div class="col-3">
<mat-form-field>
<mat-label>Height: </mat-label>
<input matInput required [(ngModel)]="blockData.height" type="number" name="height-field" id="height-field">
</mat-form-field>
</div>
<div class="col-3">
<mat-form-field>
<mat-label>Weight: </mat-label>
<input matInput required [(ngModel)]="blockData.weight" type="number" name="weight-field" id="weight-field">
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col-3">
<div class="file-field">
<div class="btn btn-primary btn-sm float-left">
<label for="image-field">Upload preview image: </label>
<input #imageField (change)="onImageSelected($event)" name="image-field" id="image-field" type="file" accept=".png, image/png" placeholder="Upload your file">
</div>
</div>
</div>
<div class="col-3">
<div class="file-field">
<div class="btn btn-primary btn-sm float-left">
<label for="zip-field">Upload models' zip: </label>
<input #zipField (change)="zipFile = $event.target.files[0];" name="zip-field" id="zip-field" type="file" placeholder="Upload your file">
</div>
</div>
</div>
</div>
<button type="submit" [disabled]="!blockForm.form.valid || imagePreview == null || zipFile == null || blockData.company === ''">Submit</button>
</div>
</form>
</div>
I hope I was clear enough, any help is appreciated :)
Finally I found the source of the problem. In our website we have integrated a Unity3D WebGL build and, if I moved from the web page with Unity to the login page, the Unity process was still running. Unity had the focus of every input of the keyboard, so it was catching all the inputs.
We resolved it by quitting the Unity application when we change page. This way, input fields can receive inputs from the keyboard again.
Another solution, maybe (I have not tested it), could be to not make Unity get the inputs, as discussed in this Unity forum's thread or by setting WebGLInput.captureAllKeyboardInput to false.

How to pass data from using POST/form leaf template?

I have a couple of major gaps in my understanding of vapor/leaf/html. I am working from the "todo" example that is created using the beta branch of vapor.
First, I made my own fluent model (no problems that I know of):
import FluentSQLite
import Vapor
final class affordatmodel: SQLiteModel {
var id: Int?
var propertyCost: String
var targetEquity: String
var interestRate: String
var amortization: String
var sponsor1: String
var sponsor2: String
var rent: String
var rentInflation: String
var propertyTaxes: String
var propertyTaxesInflation: String
var strataFees: String
var strataFeesInflation: String
init(propertyCost: String, targetEquity: String, interestRate: String, amortization: String, sponsor1: String, sponsor2: String, rent: String, rentInflation: String, propertyTaxes: String, propertyTaxesInflation: String, strataFees: String, strataFeesInflation: String) {
self.propertyCost = propertyCost
self.targetEquity = targetEquity
self.interestRate = interestRate
self.amortization = amortization
self.sponsor1 = sponsor1
self.sponsor2 = sponsor2
self.rent = rent
self.rentInflation = rentInflation
self.propertyTaxes = propertyTaxes
self.propertyTaxesInflation = propertyTaxesInflation
self.strataFees = strataFees
self.strataFeesInflation = strataFeesInflation
}
}
/// Allows to be used as a dynamic migration.
extension affordatmodel: Migration { }
/// Allows to be encoded to and decoded from HTTP messages.
extension affordatmodel: Content { }
/// Allows to be used as a dynamic parameter in route definitions.
extension affordatmodel: Parameter { }
Then I make an instance and send it to a leaf template:
let defaultData = affordatmodel(propertyCost: "700000", targetEquity: "300000", interestRate: "1", amortization: "20", sponsor1: "500000", sponsor2: "200000", rent: "1200", rentInflation: "1", propertyTaxes: "8000", propertyTaxesInflation: "1", strataFees: "0", strataFeesInflation: "0")
return leaf.render("welcome", ["affordat": defaultData])
And my Leaf template successfully populates the html with the default data (body shown here):
<body class="container">
<h1>Payment and Principal Calculations</h1>
<form action="/affordat" method="POST">
<div class="form-group">
<label for="propertyCost">Property Cost</label>
<input type="number" class="form-control" name="propertyCost" placeholder="#(affordat.propertyCost)">
</div>
<div class="form-group">
<label for="targetEquity">Target Equity</label>
<input type="number" class="form-control" name="targetEquity" placeholder="#(affordat.targetEquity)">
</div>
<div class="form-group">
<label for="interestRate">Interest Rate</label>
<input type="number" class="form-control" name="interestRate" placeholder="#(affordat.interestRate)">
</div>
<div class="form-group">
<label for="amortization">Amortization (years)</label>
<input type="number" class="form-control" name="amortization" placeholder="#(affordat.amortization)">
</div>
<div class="form-group">
<label for="sponsor1">Sponsor 1 Funds</label>
<input type="number" class="form-control" name="sponsor1" placeholder="#(affordat.sponsor1)">
</div>
<div class="form-group">
<label for="sponsor2">Sponsor 2 Funds</label>
<input type="number" class="form-control" name="sponsor2" placeholder="#(affordat.sponsor2)">
</div>
<div class="form-group">
<label for="rent">Rent</label>
<input type="number" class="form-control" name="rent" placeholder="#(affordat.rent)">
</div>
<div class="form-group">
<label for="rentInflation">Rent Inflation (will be used exactly)</label>
<input type="number" class="form-control" name="rentInflation" placeholder="#(affordat.rentInflation)">
</div>
<div class="form-group">
<label for="propertyTaxes">Property Taxes (first year est.)</label>
<input type="number" class="form-control" name="propertyTaxes" placeholder="#(affordat.propertyTaxes)">
</div>
<div class="form-group">
<label for="propertyTaxesInflation">Property Taxes Inflation (est.)</label>
<input type="number" class="form-control" name="propertyTaxesInflation" placeholder="#(affordat.propertyTaxesInflation)">
</div>
<div class="form-group">
<label for="strataFees">Strata Fees (first year est.)</label>
<input type="number" class="form-control" name="strataFees" placeholder="#(affordat.strataFees)">
</div>
<div class="form-group">
<label for="strataFeesInflation">Strata Fees Inflation (est.)</label>
<input type="number" class="form-control" name="strataFeesInflation" placeholder="#(affordat.strataFeesInflation)">
</div>
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button type="submit" class="btn btn-primary">Refresh Calculations</button>
</form>
</body>
Great, so I know how to get fluent data to HTML. My problem is I don't know how to get it back. When the "Post" occurs, the data does not seem to get passed to the controller. My route is:
router.post("affordat", use: affordatController.create)
And the relevant part of my controller looks like this:
import Vapor
final class AffordatController {
func create(_ req: Request) throws -> Future<affordatmodel> {
return try req.content.decode(affordatmodel.self).flatMap(to: affordatmodel.self) { affordatmodel1 in
return affordatmodel1.save(on: req)
}
}
}
Which shows me one of my models, with an ID #, but no data. And I kind of understand why because I didn't really seem to send the post data to the controller. How I am supposed to send the POST data to the controller? Is the problem in my leaf template, my route, or my controller?
It looks like it should work. You can inspect the data being sent to your server in the network inspector in your browser. Make sure you preserve logs and you'll be able to see the POST request and the data sent to the server.
If you breakpoint at each point in the request you can see what the data is.
As an aside, it looks like you're submitting an empty form, so it's just filling everything in as blank strings. Do you mean to use value instead of placeholder in the form inputs? Value will pre-populate the data for the user, placeholder will show the value to the user as a suggestion but won't send the data in the form submission.

App won't display all items (Ionic, Backand)

I want to make an app which displays some items, so I found the backand template (https://market.ionic.io/starters/backand-simple) and used it. I have about 40 items in my database, but the app only displays the first 20 items.
my controller.js
angular.module('SimpleRESTIonic.controllers', [])
.controller('LoginCtrl', function (Backand, $state, $rootScope, LoginService) {
var login = this;
function signin() {
LoginService.signin(login.email, login.password)
.then(function () {
onLogin();
}, function (error) {
console.log(error)
})
}
function onLogin(){
$rootScope.$broadcast('authorized');
login.email = '';
login.password = '';
$state.go('tab.dashboard');
}
function signout() {
LoginService.signout()
.then(function () {
//$state.go('tab.login');
login.email = '';
login.password = '';
$rootScope.$broadcast('logout');
$state.go($state.current, {}, {reload: true});
})
}
login.signin = signin;
login.signout = signout;
})
.controller('DashboardCtrl', function (ItemsModel, $rootScope) {
var vm = this;
function goToBackand() {
window.location = 'http://docs.backand.com';
}
function getAll() {
ItemsModel.all()
.then(function (result) {
vm.data = result.data.data;
});
}
function clearData(){
vm.data = null;
}
function create(object) {
ItemsModel.create(object)
.then(function (result) {
cancelCreate();
getAll();
});
}
function update(object) {
ItemsModel.update(object.id, object)
.then(function (result) {
cancelEditing();
getAll();
});
}
function deleteObject(id) {
ItemsModel.delete(id)
.then(function (result) {
cancelEditing();
getAll();
});
}
function initCreateForm() {
vm.newObject = {name: '', description: ''};
}
function setEdited(object) {
vm.edited = angular.copy(object);
vm.isEditing = true;
}
function isCurrent(id) {
return vm.edited !== null && vm.edited.id === id;
}
function cancelEditing() {
vm.edited = null;
vm.isEditing = false;
}
function cancelCreate() {
initCreateForm();
vm.isCreating = false;
}
vm.objects = [];
vm.edited = null;
vm.isEditing = false;
vm.isCreating = false;
vm.getAll = getAll;
vm.create = create;
vm.update = update;
vm.delete = deleteObject;
vm.setEdited = setEdited;
vm.isCurrent = isCurrent;
vm.cancelEditing = cancelEditing;
vm.cancelCreate = cancelCreate;
vm.goToBackand = goToBackand;
vm.isAuthorized = false;
$rootScope.$on('authorized', function () {
vm.isAuthorized = true;
getAll();
});
$rootScope.$on('logout', function () {
clearData();
});
if(!vm.isAuthorized){
$rootScope.$broadcast('logout');
}
initCreateForm();
getAll();
});
my services.js
angular.module('SimpleRESTIonic.services', [])
.service('APIInterceptor', function ($rootScope, $q) {
var service = this;
service.responseError = function (response) {
if (response.status === 401) {
$rootScope.$broadcast('unauthorized');
}
return $q.reject(response);
};
})
.service('ItemsModel', function ($http, Backand) {
var service = this,
baseUrl = '/1/objects/',
objectName = 'items/';
function getUrl() {
return Backand.getApiUrl() + baseUrl + objectName;
}
function getUrlForId(id) {
return getUrl() + id;
}
service.all = function () {
return $http.get(getUrl());
};
service.fetch = function (id) {
return $http.get(getUrlForId(id));
};
service.create = function (object) {
return $http.post(getUrl(), object);
};
service.update = function (id, object) {
return $http.put(getUrlForId(id), object);
};
service.delete = function (id) {
return $http.delete(getUrlForId(id));
};
})
.service('LoginService', function (Backand) {
var service = this;
service.signin = function (email, password, appName) {
//call Backand for sign in
return Backand.signin(email, password);
};
service.anonymousLogin= function(){
// don't have to do anything here,
// because we set app token att app.js
}
service.signout = function () {
return Backand.signout();
};
});
my dashboard-tab //which displays the items
<ion-view view-title="Produkte">
<div ng-if="!vm.isCreating && !vm.isEditing">
<ion-content class="padding has-header">
<!-- LIST -->
<div class="bar bar-header bar-balanced">
<span ng-click="vm.isCreating = true"><i class='icon ion-plus-round new-item'> Erstellen</i></span>
</div>
<div class="bar bar-subheader">
<div class="list card" ng-repeat="object in vm.data"
ng-class="{'active':vm.isCurrent(object.id)}">
<div class="item item-icon-right item-icon-left">
<i class="ion-compose icon" ng-click="vm.setEdited(object)"></i>
<h2 class="text-center"><b>{{object.name}}</b></h2>
<i class="icon ion-close-round" ng-click="vm.delete(object.id)"></i>
</div>
<div class="text-center">
{{object.description}}
</div>
<div class="item item-body">
<p style="text-align:center;"><img src="{{object.imgurl}}" style="max-width: 250px; max-height: 250px" /></p>
</div>
<div class="text-center">
{{object.price}} Euro
</div>
</div>
</div>
</ion-content>
</div>
<div ng-if="vm.isCreating">
<ion-content class="padding has-header">
<!-- Erstellen -->
<div class="bar bar-header">
<h2 class="title">Erstelle ein Produkt</h2>
<span ng-click="vm.cancelCreate()" class="cancel-create">Abbruch</span>
</div>
<div class="bar bar-subheader">
<form class="create-form" role="form"
ng-submit="vm.create(vm.newObject)" novalidate>
<div class="list">
<label class="item item-input item-stacked-label">
<span class="input-label">Name</span>
<input type="text" class="form-control"
ng-model="vm.newObject.name"
placeholder="Gib einen Namen ein">
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Beschreibung</span>
<textarea placeholder="Beschreibung" class="form-control"
ng-model="vm.newObject.description"></textarea>
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Preis</span>
<textarea placeholder="Preis" class="form-control"
ng-model="vm.newObject.price"
typeof="float"></textarea>
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Bild</span>
<input type="text" class="form-control"
ng-model="vm.newObject.imgurl"
placeholder="Gib einen Bildlink ein">
</label>
</div>
<button class="button button-block button-balanced" type="submit">Fertig</button>
</form>
</div>
</ion-content>
</div>
<div ng-if="vm.isEditing && !vm.isCreating">
<ion-content class="padding has-header">
<!-- Bearbeiten -->
<div class="bar bar-header bar-secondary">
<h1 class="title">Bearbeiten</h1>
<span ng-click="vm.cancelEditing()" class="cancel-create">Abbrechen</span>
</div>
<div class="bar bar-subheader">
<form class="edit-form" role="form"
ng-submit="vm.update(vm.edited)" novalidate>
<div class="list">
<label class="item item-input item-stacked-label">
<span class="input-label">Name</span>
<input type="text" class="form-control"
ng-model="vm.edited.name"
placeholder="Gib einen Namen ein">
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Beschreibung</span>
<textarea class="form-control"
ng-model="vm.edited.description"
placeholder="Beschreibung"></textarea>
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Preis</span>
<textarea placeholder="Preis" class="form-control"
ng-model="vm.edited.price"
type="float"></textarea>
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Bild</span>
<textarea class="form-control"
ng-model="vm.edited.imgurl"
placeholder="Bildlink"></textarea>
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Auswählen</span>
<textarea class="form-control"
ng-model="vm.edited.check"
placeholder="true" type="boolean"></textarea>
</label>
</div>
<button class="button button-block button-balanced" type="submit">Speichern</button>
</form>
</div>
</ion-content>
</div>
thanks for using Backand! There is a default page size filter that you can modify in your getList() call. It is available in our new SDK - if you update to the latest version of the starter project you downloaded, it should already have the appropriate changes built-in. For reference, our new SDK can be found at https://github.com/backand/vanilla-sdk
Regarding resolving your issue, in order to adjust the page size, you can pass in an additional parameter to the getList function that dynamically changes the number of records you can retrieve. Here's some sample code that matches your use case:
service.all = function () {
params = { pageSize: 100 }; // Changes page size to 100
return Backand.object.getList('items', params);
};
Using the old SDK, you can do something similar by appending the parameters query param to the URL you use to drive your GET request.

How to change URL form with GET method?

Form:
<form action="/test" method="GET">
<input name="cat3" value="1" type="checkbox">
<input name="cat3" value="5" type="checkbox">
<input name="cat3" value="8" type="checkbox">
<input name="cat3" value="18" type="checkbox">
<input type="submit" value="SUBMIT">
</form>
How to change URL form with GET method?
Before: test?cat3=1&cat3=5&cat3=8&cat3=18
After: test?cat3=1,5,8,18
I want to use jQuery.
Many thanks!
Here you go! This example, using jQuery, will grab your form elements as your question is asking and perform a GET request to the desired URL. You may notice the commas encoded as "%2C" - but those will be automatically decoded for you when you read the data on the server side.
$(document).ready(function(){
$('#myForm').submit(function() {
// Create our form object. You could optionally serialize our whole form here if there are additional parameters in the form you want
var params = {
"cat3":""
};
// Loop through the checked items named cat3 and add to our param string
$(this).children('input[name=cat3]:checked').each(function(i,obj){
if( i > 0 ) params.cat3 += ',';
params.cat3 += $(obj).val();
});
// "submit" our form by going to the properly formed GET url
var url = $(this).attr('action') + '?' + $.param( params );
// Sample alert you can remove
alert( "This form will now GET the URL: " + url );
// Perform the submission
window.location.href = url;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/test" method="GET" id="myForm">
<input name="cat3" value="1" type="checkbox">
<input name="cat3" value="5" type="checkbox">
<input name="cat3" value="8" type="checkbox">
<input name="cat3" value="18" type="checkbox">
<input type="submit" value="SUBMIT">
</form>
My friend found a solution:
$(document).ready(function() {
// Change Url Form: &cat3=0&cat3=1&cat3=2 -> &cat3=0,1,2
var changeUrlForm = function(catName){
$('form').on('submit', function(){
var myForm = $(this);
var checkbox = myForm.find("input[type=checkbox][name="+ catName +"]");
var catValue = '';
checkbox.each(function(index, element) {
var name = element.name;
var value = element.value;
if (element.checked) {
if (catValue === '') {
catValue += value;
} else {
catValue += '‚' + value;
}
element.disabled = true;
}
});
if (catValue !== '') {
myForm.append('<input type="hidden" name="' + catName + '" value="' + catValue + '" />');
}
});
};
// Press 'Enter' key
$('.search-form .inputbox-search').keypress(function(e) {
if (e.which == 13) {
changeUrlForm('cat3');
changeUrlForm('cat4');
alert(window.location.href);
}
});
// Click to submit button
$('.search-form .btn-submit').on('click', function() {
changeUrlForm('cat3');
changeUrlForm('cat4');
alert(window.location.href);
$(".search-form").submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/test" method="GET" class="search-form">
<input name="cat3" value="1" type="checkbox">1
<input name="cat3" value="3" type="checkbox">3
<input name="cat3" value="5" type="checkbox">5
<input name="cat3" value="7" type="checkbox">7
<br />
<input name="cat4" value="2" type="checkbox">2
<input name="cat4" value="4" type="checkbox">4
<input name="cat4" value="6" type="checkbox">6
<br />
<br />
Submit
<br />
<br />
<input type="text" placeholder="Search" class="inputbox-search" />
</form>