Values not getting in the drop down box in vue js - php

I am getting values from the DB to the page where the dropdown box is there but the dropdown box not returning the value. The code as shown below,
Script
methods: {
editState(id){
axios.defaults.headers.common['Authorization'] = "Bearer "+localStorage.getItem('token');
axios.get(baseUrl+'/state/edit/'+id)
.then((response) => {
alert(response.data[0].form.country_name);
this.form = response.data[0].form;
setTimeout(() => {
this.subComponentLoading = true;
}, 500);
})
.catch(function (error) {
console.log(error);
});
}
}
Vue
<d-field-group class="field-group field-row" label-for = "country_name" label="Country Name" label-class="col-4">
<d-select :options="Countries" v-model="form.country_id" id="country_id" name = "country_name" wrapper-class="col-7">
</d-select>
</d-field-group>

Two things that I see are wrong...
Countries is inside the form object but you don't assign or read it from there. Move it to the top level
You are binding a v-model to form.country_id but this does not initially exist. Add it to the form object.
To summarise...
data () {
return {
isStateEditVisible: false,
form: {
state_name: '',
isStateEnabled: true,
ISO_Code: '',
country_id: '', // 👈 added this
country_name: '',
zone_name: ''
},
Countries: [], // 👈 moved this
Zones: [] // 👈 and this
}
}
In order to react to data changes, Vue needs to know about them up-front. See https://v2.vuejs.org/v2/guide/reactivity.html

Related

Set initial value of input in vue.js formulate to data from database

I try to fetch data from a mySQL database using Axios to set the initial values of a form input generated with vue.js-formulate.
Here is my script where I want to set the initial value of "question1":
new Vue({
el: '#app',
created() {
this.fetchData();
},
data: {
row: "",
values: {
question1: this.row["answerq1"],
}
},
methods: {
fetchData() {
axios.get('retrieve.php')
.then(function (response) {
this.row = response.data;
// Checking output in Console:
console.log(this.row["answerq1"]);
});
},
}
})
The fetchData() function is working as expected, this.row["answerq1"] prints the expected string. However, access this value in the data part produces the error "this.row is undefined". I'm guessing it has something to do with the lifecycle of the created() hook but I can't figure it out.
this.row is an empty string before the API request is done, therefore you cannot access this.row["answerq1"]. You need to wait for the API request to finish.
Make this change and it should work:
data() {
return {
row: "",
values: {
question1: "" // set to empty string
}
};
}
I have found the answer to my question for anyone encountering a similar problem:
new Vue({
el: '#app',
created() {
this.fetchData();
},
data: {
row: [],
values: {
question1: null
}
},
methods: {
fetchData() {
axios.get('retrieve.php')
.then((response) => {
this.row = response.data;
this.values.question1 = this.row["answerq1"];
});
},
}
})

Laravel + Vuejs Input Form With Database Value and Update

Trying to do a simple input box. The default value should be a database value, and when user updates the value, it also updates the database. I'm using Laravel 5.5 and this is a vue component. So the initial value would be 3 from the database, but then if someone changes the value, it would also update the database. Am I on the right track with what's below, or am I way off? Currently it won't get the initial amount, and it won't update.
<template>
<div>Corn: <input v-model="corn" style="width: 50px;" /></div>
</template>
<script>
export default {
data: function() {
return {
items: 'not updated',
corn: items.cornquant
} },
watch: { // whenever amount changes, function will run
corn: function(newCorn, oldCorn) {
this.corn = '2'
this.getCorn()
} },
mounted: function() {
this.getVueItems();
},
methods: {
getVueItems: function() {
axios.get('/testing').then(response => {
this.items = response.data;
}); },
getCorn: _.debounce(
function() {
this.corn = 'Thinking...'
var vm = this
axios.put('/corn/{amount}').then(response => {
vm.corn = response.data;
}) },
// milliseconds we wait for user to stop typing.
500
) }, }
</script>
And here's the route (did a little editing, this updates now):
Route::post('/corn', function () {
$test = App\Resource::where('user_id', Auth::id())->update(['cornquant' => request('amount')]);
return $test;
});
Use an es6 arrow function in debounce to preserve this. Then remove var vm = this and assign to corn like this.corn = response.data.
And where are you initially calling getCorn?
Got everything sorted. Defining default values was the hardest part, but ended up being easy enough!
Here's the vue template file:
<template>
<div>Corn: <input v-model="corn" style="width: 50px;" /></div>
</template>
<script>
export default {
data: function() {
return {
items: 'not updated',
corn: '0'
} },
watch: { // whenever input amount changes, function will run
corn: function() {
this.getCorn()
} },
mounted: function() {
this.getVueItems(); //this will call the actual corn value to put as the default value
},
methods: {
getVueItems: function() {
axios.get('/testing').then(response => {
this.items = response.data;
this.corn = response.data.cornlq; //set initial value
}); },
getCorn: _.debounce(
function() {
var vm = this
axios.post('/corn', { //updates database
corn: this.corn,
}).then(response => {
vm.corn = response.data.cornlq; //keeps actual database value in input
}) },
2000
) }, }
</script>
And the route:
Route::post('/corn', function () {
App\Resource::where('user_id', Auth::id())->update(['cornlq' => request('corn')]); //update database with new amount
$result = App\Resource::where('user_id', Auth::id())->first(); //save all amounts to $result
return $result; //return result so I can update the vue
});

select2 drop-down plugin with auto-populate together with add new record

I'm now working with select2 drop-down plugin. I came situation that I have to add a select2 field which auto populate the existing mail id's in our app. I was able to do so, but I also has to add new mail id's which are not in our app in same field. I do not able work it out. Can any of you please help me out from this...
Here is my view page code.
<input type="hidden" class="select2 to_email w-100" name="to_email[]"
data-role="to_email" data-width="100%" data-placeholder="To" value="">
Js code:
$('body').on('click','[data-button="reply-mail"],[data-click="reply"]', function() {
attach = [];
var $ti = $(this).closest('[data-role="row-list"]').find('[data-role="reply-mail-wrap"]');
var $to_this = $ti.find('[data-role="to_email"]');
var mail_toadr = $ti.find('input[name="to_addr"]').val();
$($to_this).select2({
placeholder: "Search for a contact",
minimumInputLength: 3,
//maximumSelectionLength: 1,
multiple : true,
ajax: {
url: Utils.siteUrl()+'mailbox/get_all_contacts',
type: 'POST',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
term: term, //search term
page_limit: 100 // page size
};
},
results: function (data, page) {
return { results: data};
}
},
initSelection: function(element, callback) {
return $.getJSON(Utils.siteUrl()+'mailbox/get_all_contacts?email=' + (mail_toadr), null, function(data) {
return callback(data);
});
}
});
});
I know, working example could be better to you, but I'm sorry, I do not know how to do it.
A screen shot for small help:http://awesomescreenshot.com/08264xy485
Kindly help..
I have got a fix for my requirement. If we enter a non-existing value in our field, results: function (data, page) {...} returns an empty array. We can check this as:
results: function (data, page) {
for (var obj in data) {
id = JSON.stringify(data[obj].id);
text = JSON.stringify(data[obj].text);
if (id == '"0"') {
$ti.find('.to_email').select2('val', '<li class="select2-search-choice"><div>'+ text +'</div><a tabindex="-1" class="select2-search-choice-close" onclick="return false;" href="#"></a></li>');
}
}
return { results: data};
}
But, better than this I suggest you to do a check in the area where we fetch result (here: Utils.siteUrl()+'mailbox/get_all_contacts'). I have done this to fix my issue:
function get_all_contacts()
{
// $contacts is the result array from DB.
// $term is the text to search, eg: 111
foreach($contacts as $contact_row) {
$contact_all[] = array('id' => $contact_row['id'], 'text' => $contact_row['primary_email']);
}
if (empty($contact_all)) {
$contact_all = array('0' => array('id' => 'undefinedMAILID_'. $term, 'text' => $term ) );
}
$contact_data['results'] = $contact_all;
send_json_response($contact_all);
}
Getting value in JS:
sel_ids = $('.to_email').select2('val');
console.log(sel_ids);
// console will show - ["value if mail id is existing", "undefinedMAILID_111"]
hope this will help someone.

Linked/chained MagicSuggest dropdowns?

I am trying to build a set of linked/chained multiselect boxes using MagicSuggest and a php query. So, first I build a MagicSuggest box with a function for when ms1 is changed:
$(document).ready(function() {
var ms1 = $('#ms1').magicSuggest({
data: 'datams1.php',
displayField: 'name' });
$(ms1).on('selectionchange', function(event, combo, selection){
run(selection);});
});
Then I build a new MagicSuggest box by running a php query that returns a json object:
function run(country) {
$.getJSON("query.php", { id: country[0].id}, callbackFuncWithData );
}
function callbackFuncWithData(region) {
var ms2 = $('#ms2').magicSuggest({
data: region,
displayField: 'name'
});
}
This works once I make an initial selection, but does not update if I change the selection. I have checked and within my "callbackFuncWithData" I am producing an updated "region" json object. So it might just be that I need to refresh/reload my #ms2 object.
My questions are:
Is there a way to force an refresh of the MagicSuggest data?
Is there a better/cleaner/more efficient way to use the results of one MagicSuggest box to query and return the data for a second, linked MagicSuggest box?
Thanks!
use setData() method to dynamically set the data when needed.
you can always use a library like angular to bind the component properties together.
This code makes 2 linked combos with the same data, but one of them shows the "name" field and the other one shows the "name1" filed.
function reflectSelection(ms1, ms2){
var val = parseInt(ms1.getValue());
var val1 = parseInt(ms2.getValue());
if(!isNaN(val)){
if(val != val1){
ms2.clear(true);
ms2.setSelection(ms1.getSelection());
}
}
else
{
ms2.clear(true);
}
}
var msName = $('#ms-onselectionchange').magicSuggest({
maxSelectionRenderer: function(){ return ''; },
useTabKey: true,
noSuggestionText: '',
strictSuggest: true,
maxSelection: 1,
allowFreeEntries: false,
placeholder : '',
data: [{'id':0, 'name':'Paris', 'name1':'Paris5'}, {'id':1, 'name':'New York', 'name1':'New York5'}],
});
var msName1 = $('#ms-onselectionchange1').magicSuggest({
maxSelectionRenderer: function(){ return ''; },
useTabKey: true,
noSuggestionText: '',
displayField: 'name1',
strictSuggest: true,
maxSelection: 1,
allowFreeEntries: false,
placeholder : '',
data: [{'id':0, 'name':'Paris', 'name1':'Paris5'}, {'id':1, 'name':'New York', 'name1':'New York5'}],
});
$(msName).on('selectionchange', function(e,m){
reflectSelection(msName, msName1);
});
$(msName1).on('selectionchange', function(e,m){
reflectSelection(msName1, msName);
});

How to render different view on selecting tabs in ext js4?

1)I have a json file which I want to display in view.
{
"contents": [
{
"title":'JWorld',
"image":'image/e-learning/elearning.png',
"subtitle":[
{
"categories":'Aus',
},
{
"categories":'England',
}
]
},
{
"title":'JIndia',
"image":'image/Content/History_of_India.jpg',
"subtitle":[
{
"categories":'History',
},
{
"categories":'India palace',
}
]
},
{
"title":'JMaharastra',
"image":'image/Content/Geography.jpg',
"subtitle":[
{
"categories":'History Maharastra',
},
{
"categories":'Maharastra Heros',
}
]
}
]
}
2)My view file :--
Ext.define('Balaee.view.kp.dnycontentcategories.ContentcategoriesView',
{
extend:'Ext.view.View',
id:'contentcategoriesViewId',
alias:'widget.ContentcategoriesView',
store:'kp.DnycontentcategoriesStore',
config:
{
tpl:'<tpl for="0">'+
'<div class="main">'+
'</br>'+
'<b>{title}</b></br>'+
'<img src={image} hight="50" width="100"></br>'+
'</div>'+
'</tpl>',
itemSelector:'div.main',
}
});// End of class
3) i am using tab panel and dynamically adding tabs in it using json file.
Ext.define('Balaee.view.kp.dnycontentcategories.Contentcategories',{
extend:'Ext.tab.Panel',
requires:[
'Balaee.view.kp.dnycontentcategories.ContentcategoriesView','Balaee.view.kp.dnycontentcategories.ContentcategoriesView1'
],
id:'contentcategoriesId',
alias:'widget.Contentcategories',
height:500,
items:[
],//end of items square
});// End of login class
4) My store file:--
Ext.define('Balaee.store.kp.DnycontentcategoriesStore',{
extend: 'Ext.data.Store',
model: 'Balaee.model.kp.DnycontentcategoriesModel',
autoLoad:true,
// filters: [{
// property: 'title',
// }],
proxy:
{
type:'ajax',
api:
{
read:'data/content.json',
//create: ,
//update: ,
//destroy: ,
},//End of api
reader:
{
type:'json',
root:'contents',
//successProperty: ,
}//End of reader
}//End of proxy
});//End
5) My Controller file some code
here I am dynamically adding some tabs from json file.And selecting particular tab I want different particular values from json file. But I get same view of first tab. How can I solve this problem.
init: function(){
console.log("inside content controller");
this.control({
'Contentcategories':
{
render:this.renderFunction,
}
});//End of control
},//End of init() function
renderFunction:function(){
console.log("Inside render function");
var tabPanel = Ext.getCmp('contentcategoriesId'); // tabpanel
var tabPanelView = Ext.getCmp('contentcategoriesViewId'); // tabpanel view
var storeObject= this.getStore('kp.DnycontentcategoriesStore'); // store
storeObject.on('load',function(){
storeObject.each(function(model){
//tabPanelView.store().filter('title',model.get('title')),
console.log(model.get('title'));
console.log(model.get('categories'));
tabPanel.add({title:model.get('title'),
id:model.get('title'),
//html:"<image src=model.get('image')>",
xtype:'ContentcategoriesView',
}); //End of add function
});// End of storeObject function
tabPanel.setActiveTab(0);
});
},// End of render function
please give me some suggestion.
There are a few issues with your code.
You define ContentcategoriesView - its a a component you have extended; but you give it an id (contentcategoriesId) yet you are creating more than one of these components - it makes no sense as an id has to be unique per component instance.
Then, you attach a store to this view, which means all components will render the same.
If I understand correctly you want each entry in your json to become a different tab.
I would take this direction (code not tested, but should give you a direction):
Ext.define('Balaee.view.kp.dnycontentcategories.ContentcategoriesView',
{
extend:'Ext.panel.Panel', // Notice it's a panel.
alias:'widget.ContentcategoriesView',
config:
{
tpl: '<div class="main">' +
'</br>' +
'<b>{title}</b></br>' +
'<img src={image} hight="50" width="100"></br>' +
'</div>'
itemSelector:'div.main',
}
});
And then:
storeObject.on( 'load',function() {
storeObject.each( function( model ) {
tabPanel.add({
xtype: 'ContentcategoriesView',
title: model.get( 'title' ),
id: model.get( 'title' ),
data: model
});
});
tabPanel.setActiveTab(0);
});

Categories