Vue.js Component combined with Laravel Form Validation (i.e. passing an initial value for data) - laravel

After much Googling and finding the Vue.js forum down, I am ready to give up.
I'm creating a Postcode Lookup component, and everything was working well until I tried to combine it with Laravel's form validation - particularly when there's an error, and the form re-fills the old values.
Hopefully I cover everything here. I have a form input partial that I use which generates every form input. It also uses Laravel's old(...) value if present.
The issue is because there's a default value (in this case for postcode and address) of an empty string, this overrides the value attribute of Postcode input, and the content of the Address textarea.
In made up land, the ideal would be:
data : function() {
return {
postcode : old('postcode'),
address : old('address'),
addresses : [],
hasResponse : false,
selectedAddress : ''
};
},
So that's what I'm trying to replicate.
I can probably replace validation with Ajax validation, but my form partial changes the appearance of fields with an error slightly, so this would be messy
From my understanding:
I can't set an initial data value, as this will override the input value.
I can set a prop, but this is immutable
Any help I can find suggests 'using a computed property which determines its value from the prop' but if you literally do that, it doesn't update.
Here's what I have so far:
<so-postcode-lookup initial-postcode="{{ old('postcode') }}" initial-address="{{ old('address') }}"></so-postcode-lookup>
/**
* Allow user to select an address from those found in the postcode database
*/
Vue.component('so-postcode-lookup', {
name : 'so-postcode-lookup',
template : '#so-postcode-lookup-template',
props : ['initialPostcode', 'initialAddress'],
data : function() {
return {
postcode : '',
address : '',
addresses : [],
hasResponse : false,
selectedAddress : ''
};
},
computed : {
currentAddress : function() {
if (this.address !== '') {
return this.address;
} else {
return this.initialAddress;
}
},
currentPostcode : function() {
if (this.postcode !== '') {
return this.postcode;
} else {
return this.initialPostcode;
}
},
hasAddresses : function() {
return this.addresses.length;
},
isValidPostcode : function() {
return this.postcode !== '' && this.postcode.length > 4;
},
isInvalidPostcode : function() {
return !this.isValidPostcode;
}
},
methods : {
fetchAddresses : function() {
var resource = this.$resource(lang.ajax.apiPath + '/postcode-lookup{/postcode}');
var $vm = this;
var element = event.currentTarget;
// Fetch addresses from API
resource.get({ postcode : this.postcode }).then(function(response) {
response = response.body;
if (response.status == 'success') {
// Update addresses property, allowing select to be displayed
$vm.addresses = response.data;
} else {
$vm.addresses = [];
}
this.hasResponse = true;
});
},
setAddress : function() {
this.address = this.selectedAddress;
}
}
});
<template id="so-postcode-lookup-template">
<div class="row">
#include('partials.input', [
'label' => trans('register.form.postcode'),
'sub_type' => 'postcode',
'input_id' => 'postcode',
'autocorrect' => false,
'input_attributes' => 'v-model="currentPostcode"',
'suffix_button' => true,
'suffix_button_reactive' => trans('register.form.postcode_button_reactive'),
'suffix_text' => trans('register.form.postcode_button'),
'required' => true,
'columns' => 'col-med-50',
'wrapper' => 'postcode-wrapper'
])
<div class="col-med-50 form__item" v-show="hasResponse">
<label for="address-selector" class="form__label" v-show="hasAddresses">{{ trans('forms.select_address') }}</label>
<select id="address-selector" class="form__select" v-show="hasAddresses" v-model="selectedAddress" #change="setAddress">
<template v-for="address in addresses">
<option :value="address.value">#{{ address.text }}</option>
</template>
</select>
<so-alert type="error" allow-close="false" v-show="!hasAddresses">{{ trans('forms.no_addresses') }}</so-alert>
</div>
#include('partials.input', [
'label' => trans('register.form.address'),
'input_id' => 'address',
'type' => 'textarea',
'input_attributes' => 'v-model="currentAddress"',
'required' => true
])
</div>
</template>
If I try this, and set the model of the inputs to currentPostcode and currentAddress respectively, I seem to get an infinite loop.
I think I'm overthinking this somehow.

You can't bind directly to a prop but you can set an initial value using the prop and then bind to that, which is the way to go if you need a two way binding:
Vue.component('my-input', {
props: {
'init-postcode': {
default: ""
}
},
created() {
// copy postcode to data
this.postcode = this.initPostcode;
},
data() {
return {
postcode: ""
}
},
template: '<span><input type="text" v-model="postcode"> {{ postcode }}</span>'
});
Then just do:
<div id="app">
<my-input init-postcode="{{ old('postcode') }}"></my-input>
</div>
Here's the fiddle: https://jsfiddle.net/vL5nw95x/
If you are just trying to set the initial values, but don't need a two way binding, then you can reference the prop directly - as you won't be applying any changes - using v-bind:value:
Vue.component('my-input', {
props: {
'init-postcode': {
default: ""
}
},
template: '<span><input type="text" :value="initPostcode"> {{ postcode }}</span>'
});
And the markup:
Here's the fiddle: https://jsfiddle.net/pfdgq724/

Im working in a easy way to do that using laravel 5.4 controller to send the data directly
In Laravel view:
<input class="form-control" id="ciudad" name="ciudad" type="text" v-model="documento.ciudad" value="{{ old('ciudad', isset($documento->ciudad) ? $documento->ciudad : null) }}" >
in vue.js 2.0
data: {
documento: {
ciudad: $('#ciudad').val(),
},
},
In Laravel Controller
$documento = ReduJornada::where("id_documento",$id)->first();
return view('documentos.redujornada')->with(compact('documento'));

Related

passing component state to redux-form onSubmit

novice user of redux-form here. I have a signin modal that has 2 different operations: login and register. The role (stored in component state) will be login by default, and the user will be able to click a button to change it to register.
Where I'm stuck, is that I want to pass that piece of state to the onSubmit() function, so that I can dispatch the correct actions depending on if the user is trying to login or register.
My thinking was that I could pass down this piece of state called signInType as a prop to the function. Of course, it is not working as I would have expected. I can pass in a prop via the reduxForm HOC, but from that function I cannot access the component's state.
Here are the relevant parts of my component to help understand what my end goal is here:
const [signInType, setSignInType] = useState('login')
const onSubmit = (data, dispatch, props) => {
console.log('props: ', props);
if (props.signInType === 'login') {
return (
api.post('/Login', data)
.then(json => {
const response = JSON.parse(json.d)
if (!response.userid) {
console.error(response.message)
dispatch(emailLoginFailure(response.message))
return response.message
}
LogRocket.identify(response.userid, {
email: data.email,
})
dispatch(emailLoginSuccess(response))
})
.catch(err => {
console.error(err)
dispatch(emailLoginFailure(err))
})
)
} else if (props.signInType === 'register') {
return (
api.post('/RegisterByEmail', {
email: data.email,
password: data.password,
utm_source: "Development",
utm_medium: "email",
utm_campaign: "Campaign Test",
utm_term: "N/A",
utm_content: "123",
utm_date: "2019-02-11 12:25:36"
})
.then(json => {
const response = JSON.parse(json.d)
if (!response.userid) {
console.error(response.message)
dispatch(emailRegisterFailure(response.message))
return response.message
}
// LogRocket.identify(response.userid, {
// email: data.email,
// })
dispatch(emailRegisterSuccess(response))
})
.catch(err => {
console.error("Unable to register email:", err)
})
)
} else {
console.error("error: No signin type?")
}
}
Thanks for the help :)
Such login/register flow I prefer handling it with different components, in order to respect and follow SRP.
Also, I'm not sure how do you organize your components, but here's how I deal with such a scenario:
Your Modal:
* It will be responsible only for rendering Login or Register forms.
const Modal = () => {
const [signInType, ] = useState('login')
const isLogin = signInType === 'login'
return <>
{ isLogin ? <LoginForm /> : <RegisterForm /> }
<button onClick={() => setSignInType(isLogin ? 'register' : 'login')}>
{ isLogin ? 'Sign up' : 'Sign in' }
</button>
</>
}
LoginForm:
* Now you can pass your login action to onSubmit prop. Login will be your presentation component, while LoginForm decorates Login with reduxForm HOC.
export default reduxForm({
form: 'login',
onSubmit: data => {}
})(Login)
RegisterForm:
* Here we follow the same idea as LoginForm.
export default reduxForm({
form: 'register',
onSubmit: data => {}
})(Register)

Laravel vue show old data on update fields

So I've made update function for my component and it's working perfectly the only issue is I cannot show old data (if there is any) to the user,
This is what I have now:
As you see not only i can send my form data to back-end for update, but also I have the saved data already.
Code
export default {
data: function () {
return {
info: '', //getting data from database
profile: { //sending new data to back-end
photo: '',
about: '',
website: '',
phone: '',
state: '',
city: '',
user_id: '',
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
}
}
},
mounted: function() {
this.isLoggedIn = localStorage.getItem('testApp.jwt') != null;
this.getInfo();
},
beforeMount(){
if (localStorage.getItem('testApp.jwt') != null) {
this.user = JSON.parse(localStorage.getItem('testApp.user'))
axios.defaults.headers.common['Content-Type'] = 'application/json'
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('testApp.jwt');
console.log()
}
},
methods: {
update() { // sending data to back-end
let user_id = this.user.id;
let photo = this.profile.photo;
let about = this.profile.about;
let website = this.profile.website;
let phone = this.profile.phone;
let state = this.profile.state;
let city = this.profile.city;
axios.put('/api/updateprofile/'+ user_id, {user_id, photo, about, website, phone, state, city}).then((response) => {
this.$router.push('/profile');
$(".msg").append('<div class="alert alert-success" role="alert">Your profile updated successfully.</div>').delay(1000).fadeOut(2000);
});
Vue.nextTick(function () {
$('[data-toggle="tooltip"]').tooltip();
})
},
getInfo: function() { //getting current data from database
let user_id = this.user.id;
axios.get('/api/show/'+ user_id).then((response) => {
this.info = response.data;
console.log(response);
});
},
}
}
Component sample field
// this shows my about column from database
{{info.about}}
// this sends new data to replace about column
<textarea name="about" id="about" cols="30" rows="10" class="form-control" v-model="profile.about" placeholder="Tentang saya..."></textarea>
Question
How to pass old data to my fields (sample above)?
Update
Please open image in big size.
This can be done by assigning this.profile the value of this.info on your Ajax response.
This way you will have input fields set up with original values.
function callMe() {
var vm = new Vue({
el: '#root',
data: {
profile:{},
info:{}
},
methods: {
getInfo: function() { //getting current data from database
this.info={about:"old data"}//your response here
this.profile=Object.assign({},this.info);
},
},
})
}
callMe();
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.11/dist/vue.js"></script>
<div id='root'>
<button #click="getInfo">Ajax Call click me</button>
Input <input v-model="profile.about"/>
<p>profile:{{this.profile}}</p>
<p>info: {{this.info}}</p>
</div>
The problem with the code is that after assigning new value info is not reactive anymore. You need to keep "info" like this in the start.
info: { // data from api
photo: '',
about: '',
website: '',
phone: '',
state: '',
city: '',
user_id: '',
}
And after fetching values from api update each value separately.
getInfo: function() { //getting current data from database
let user_id = this.user.id;
axios.get('/api/show/'+ user_id).then((response) => {
this.info.photo = response.data.photo;
this.info.about = response.data.about;
//all other values
console.log(response);
});
},
In your textarea you have a model profile.about, the way to show the "old data", is to assing to that model the data
in the create or mounted method you have to assing like
this.profile.about = this.info.about
this way profile.about will have the data stored in your db, that way if the user update it, the old data will be keep safe in this.info.about and the edited in this.profile.about

Vuejs 2 using filterBy and orderBy in the same computed property

I am having a hard time trying to joing a filterBy with orderBy, on vuejs 2.0, with all research I have found about this subject, as of link on the bottom of my question.
This is my filter, which is working:
// computed() {...
filteredResults() {
var self = this
return self.results
.filter(result => result.name.indexOf(self.filterName) !== -1)
}
A method called in the component:
// methods() {...
customFilter(ev, property, value) {
ev.preventDefault()
this.filterBook = value
}
In the component:
// Inside my component
Name..
And another filter, which works as well:
// computed() {...
orderByResults: function() {
return _.orderBy(this.results, this.sortProperty, this.sortDirection)
}
To comply with my orderBy I have this method:
// methods() {...
sort(ev, property) {
ev.preventDefault()
if (this.sortDirection == 'asc' && this.sortProperty == property ) {
this.sortDirection = 'desc'
} else {
this.sortDirection = 'asc'
}
this.sortProperty = property
}
And to call it I have the following:
// Inside my component
Name..
I have found in the docs how we use this OrderBy, and in this very long conversation how to use filter joint with sort, but I could really not implement it...
Which should be some like this:
filteredThings () {
return this.things
.filter(item => item.title.indexOf('foo') > -1)
.sort((a, b) => a.bar > b.bar ? 1 : -1)
.slice(0, 5)
}
I could not make this work...
I tried in many forms as of:
.sort((self.sortProperty, self.sortDirection) => this.sortDirection == 'asc' && this.sortProperty == property ? this.sortDirection = 'desc' : this.sortDirection = 'asc' )
But still, or it does not compile or it comes with errors, such as:
property not defined (which is defines such as I am using it in the other method)
method of funcion not found (is happens when comment my method sort.. maybe here is what I am missing something)
Thanks for any help!
The ideas of your approach seem valid, but without a full example it's hard to tell what might actually be wrong.
Here's a simple example of sorting and filtering combined. The code can easily be extended e.g. to work with arbitrary fields in the test data. The filtering and sorting is done in the same computed property, based on the parameters set from the outside. Here's a working JSFiddle.
<div id="app">
<div>{{filteredAndSortedData}}</div>
<div>
<input type="text" v-model="filterValue" placeholder="Filter">
<button #click="invertSort()">Sort asc/desc</button>
</div>
</div>
<script>
new Vue({
el: '#app',
data() {
return {
testData: [{name:'foo'}, {name:'bar'}, {name:'foobar'}, {name:'test'}],
filterValue: '',
sortAsc: true
};
},
computed: {
filteredAndSortedData() {
// Apply filter first
let result = this.testData;
if (this.filterValue) {
result = result.filter(item => item.name.includes(this.filterValue));
}
// Sort the remaining values
let ascDesc = this.sortAsc ? 1 : -1;
return result.sort((a, b) => ascDesc * a.name.localeCompare(b.name));
}
},
methods: {
invertSort() {
this.sortAsc = !this.sortAsc;
}
}
});
</script>

Vue-Multiselect with Laravel 5.3

I'm new to Laravel and Vue and need help implementing Vue-Multiselect.
I don't know how to pass the actual options to the select.
My vue file:
<template>
<div class="dropdown">
<multiselect
:selected.sync="selected"
:show-labels="false"
:options="options"
:placeholder="placeholder"
:searchable="false"
:allow-empty="false"
:multiple="false"
key="name"
label="name"
></multiselect>
<label v-show="showLabel" for="multiselect"><span></span>Language</label>
</div>
</template>
<script>
import { Multiselect } from 'vue-multiselect';
export default {
components: { Multiselect },
props: {
options: {},
placeholder: {
default: 'Select one'
},
showLabel: {
type: Boolean,
default: true
},
selected: ''
}
};
</script>
My blade file:
<div class="form-group">
<drop-down
:options="{{ $members->list }}"
:selected.sync="selected"
:show-label="false"
></drop-down>
</div>
In my controller method I tried a few things:
1.
public function edit($id)
{
....
$members_list = Member::orderBy('member_first_name')->pluck('member_first_name', member_id');
return view('businesses.edit', compact('members_list'));
}
I got this error:
[Vue warn]: Invalid prop: type check failed for prop "options". Expected Array, got Object. (found in component: ).
2.I tried:
$members = Member::orderBy('member_first_name')->pluck('member_first_name', member_id');
$members_list = $members->all();
return view('businesses.edit', compact('members_list'));
I got this error:
htmlspecialchars() expects parameter 1 to be string, array given (View: C:\wamp\www\ccf.local\resources\views\businesses\edit.blade.php)
3.
$members = DB::table('members')
->orderBy('member_first_name', 'asc')
->get();
$members_list = array();
foreach($members as $mem) {
$members_list[$mem->member_id] = $mem->member_first_name;
}
I got this error: htmlspecialchars() expects parameter 1 to be string, array given (View: C:\wamp\www\ccf.local\resources\views\businesses\edit.blade.php)
So I need help with 2 things:
How to send the $members_list as the options
How can I combine the member_first_name and member_last_name fields so I can get options like this:
option value="member_id"
option text = member_first_name member_last_name
Thank you
When using prop binding inside of laravel {{ }} tries to output an escaped form of the variable.
what you need is a javascript array. if $members_list returns a collection, which seems to be indicated by your other code, try
<drop-down
:options="{{ $members_list->toJson() }}"
:selected.sync="selected"
:show-label="false"
></drop-down>
as for your controller this will help
$members = DB::table('members')
->orderBy('member_first_name', 'asc')
->get();
$members_list = $members->map(
function($member) {
return [
"value" => $member->member_id,
"label" => $member->member_first_name. " ". $member->member_last_name
];
}
);
Laravel Collections have a good selection of function that help to manipulate data will map your members array to the structure of { value: "", label: "" } when you convert to Json.
Lastly don't forget to set up your prop bindings in vue.
props: {
options: {
type: Array,
default: function() {
return [];
}
},...
}
That should get you going.

Angular 2 (Beta) Server side validation messages

I am looking for an elegant way to display validation messages from a server side API without having to create custom validators or hard coding all possible messages in the UI.
I need to add error messages to specific fields as well as to the entire form.
This must work in Angular 2.0.0-beta.3
There are two kinds of server validations:
The global ones (for the whole form or corresponding to an error during the form submission)
The ones related to fields
For the one, simply extract the message from the response payload and put it into a property of your component to display it into the associated template:
#Component({
(...)
template: `
<form (submit)="onSubmit()">
(...)
<div *ngIf="errorMessage">{{errorMessage}}</div>
<button type="submit">Submit</button>
</form>
`
})
export class MyComponent {
(...)
onSubmit() {
this.http.post('http://...', data)
.map(res => res.json())
.subscribe(
(data) => {
// Success callback
},
(errorData) => {
// Error callback
var error = errorData.json();
this.error = `${error.reasonPhrase} (${error.code})`;
}
);
}
}
I assume that the response payload for error is a JSON one and corresponds to the following:
{
"code": 422,
"description": "Some description",
"reasonPhrase": "Unprocessable Entity"
}
For the second one, you can set received error message within controls associated with form inputs, as described below:
#Component({
(...)
template: `
<form [ngFormModel]="myForm" (submit)="onSubmit()">
(...)
Name: <input [ngFormControl]="myForm.controls.name"/>
<span *ngIf="myForm.controls.name.errors?.remote"></span>
(...)
<button type="submit">Submit</button>
</form>
`
})
export class MyComponent {
(...)
constructor(builder:FormBuilder) {
this.myForm = this.companyForm = builder.group({
name: ['', Validators.required ]
});
}
onSubmit() {
this.http.post('http://...', data)
.map(res => res.json())
.subscribe(
(data) => {
// Success callback
},
(errorData) => {
// Error callback
var error = errorData.json();
var messages = error.messages;
messages.forEach((message) => {
this.companyForm.controls[message.property].setErrors({
remote: message.message });
});
}
);
}
}
I assume that the response payload for error is a JSON one and corresponds to the following:
{
messages: [
{
"property": "name",
"message": "The value can't be empty"
]
}
For more details you can have a look at this project:
https://github.com/restlet/restlet-sample-angular2-forms/blob/master/src/app/components/company.details.ts
https://github.com/restlet/restlet-sample-angular2-forms/blob/master/src/app/components/form.field.ts
I present you the definitive displayErrors function (Handles server side validations following the JSONAPI Standard):
You will need Underscore.js
displayErrors(error: ErrorResponse) {
let controls = this.supportRequestForm.controls;
let grouped = _.groupBy(error['errors'], function(e) {
return e['source']['pointer'];
});
_.each(grouped, function(value, key, object) {
let attribute = key.split('/').pop();
let details = _.map(value, function(item) { return item['detail']; });
controls[attribute].setErrors({ remote: details.join(', ') });
});
}

Resources