How to send object with an object inside to server Vue.js 3 - spring

I need to send object to the server:
{
"id": "null",
"indexNumber": "1454",
"indexYear": "2021",
"firstName": "John",
"lastName": "Doe",
"email": "john#doe.com",
"address": "John Doe Street 1231",
"city": {
"postalCode": 10000,
"name": "New York"
} ,
"currentYearOfStudy": 1
}
when I use to test it from postman everything is fine, but when I try to send object "student" from frontend i got this error message "Cannot read property 'postalCode' of undefined:
Where do I need to define this property, or where to define object city, how to do this?
inserStudent() {
StudentService.insertStudent({
indexNumber: this.indexNumber,
indexYear: this.indexYear,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
address: this.address,
postalCode: this.city.postalCode,
name: this.city.name,
currentYearOfStudy: this.currentYearOfStudy
})
.then((response) => {
console.log("Student inserted!" + response);
addMessage({
message: "Student inserted!",
type: "success",
title: "STUDENT",
});
})
.catch((error) => {
addMessage({
message: "Insert was not successful:" + error,
type: "danger",
title: "Insert student",
});
});
}
Sorry I'm new to vue...
<template>
<div class="form-container m-4 col-6 col-md-8 col-sm-10 mx-auto" display-inline-block>
<h3 v-if="actionType === 'new'">New Student</h3>
<h3 v-else>Edit Student</h3>
<MyInputComponent
name="indexNumber"
label="Index Number"
v-model="indexNumber"
:vcomp="v$.indexNumber"
></MyInputComponent>
<MyInputComponent
name="indexYear"
label="Index Year"
v-model="indexYear"
:vcomp="v$.indexYear" >
</MyInputComponent>
<MyInputComponent
name="firstName"
label="First Name"
v-model="firstName"
:vcomp="v$.firstName"
>
</MyInputComponent>
<MyInputComponent
name="lastName"
label="Last Name"
v-model="lastName"
:vcomp="v$.lastName"
>
</MyInputComponent>
<MyInputComponent
name="email"
label="Email"
v-model="email"
:vcomp="v$.email"
>
</MyInputComponent>
<MyInputComponent
name="address"
label="Address"
v-model="address"
:vcomp="v$.address"
>
</MyInputComponent>
<MyInputComponent
name="postalCode"
label="Postal Code"
v-model="postalCode"
:vcomp="v$.postalCode"
>
</MyInputComponent>
<MyInputComponent
name="name"
label="City Name"
v-model="name"
:vcomp="v$.name"
>
</MyInputComponent>
<MyInputComponent
name="currentYearOfStudy"
label="Curent Year Of Study"
v-model="currentYearOfStudy"
:vcomp="v$.currentYearOfStudy"
>
</MyInputComponent>
<div class="d-flex flex-row-reverse">
<button class="btn btn-outline-primary" #click="saveStudent">Save</button>
</div>
</div>
</template>
<script>
import useValidate from "#vuelidate/core";
import {
required,
minLength,
maxLength,
email,
maxValue,
minValue,
} from "#vuelidate/validators";
import MyInputComponent from "#/components/inputs/MyInputControl.vue";
import StudentService from "#/services/StudentService.js";
import { addMessage } from "#/main.js";
export default {
components: { MyInputComponent },
props: {
studentId: {
type: String,
},
actionType: {
type: String,
},
},
created() {
if (this.studentId) {
StudentService.getStudent(this.studentId).then((response) => {
const student = response.data;
this.indexNumber = student.indexNumber;
this.indexYear = student.indexYear;
this.firstName = student.firstName;
this.lastName = student.lastName;
this.email = student.email;
this.address = student.address;
this.postalCode = student.city.postalCode;
this.name = student.city.name;
this.currentYearOfStudy = student.currentYearOfStudy;
});
}
},
data() {
return {
v$: useValidate(),
id:null,
indexNumber: "",
indexYear: "",
firstName: "",
lastName: "",
email: "",
address: "",
postalCode: "",
name: "",
currentYearOfStudy: null,
randomNumber:''
};
},
validations() {
return {
indexNumber: {
required,
minLength: minLength(4),
maxLength: maxLength(4),
},
indexYear: {
required,
minLength: minLength(4),
maxLength: maxLength(4),
},
firstName: {
required,
minLength: minLength(3),
maxLength: maxLength(30),
},
lastName: {
required,
minLength: minLength(3),
maxLength: maxLength(30),
},
email: {
required,
email,
},
address: {
required,
minLength: minLength(3),
},
postalCode:{
required,
minValue: minValue(9999),
maxValue: maxValue(100000),
},
name:{
required,
minLength: minLength(3),
maxLength: maxLength(30)
},
currentYearOfStudy: {
required,
minValue: minValue(1),
maxValue: maxValue(5),
},
};
},
methods: {
saveStudent() {
if (this.actionType && this.actionType === "new") {
this.inserStudent();
} else {
this.updateStudent();
}
},
inserStudent() {
StudentService.insertStudent({
indexNumber: this.indexNumber,
indexYear: this.indexYear,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
address: this.address,
postalCode: this.city.postalCode,
name: this.city.name,
currentYearOfStudy: this.currentYearOfStudy
})
.then((response) => {
console.log("Student inserted!" + response);
addMessage({
message: "Student inserted!",
type: "success",
title: "STUDENT",
});
})
.catch((error) => {
addMessage({
message: "Insert was not successful:" + error,
type: "danger",
title: "Insert student",
});
});
},
updateStudent() {
StudentService.editStudent({
id: this.studentId,
indexNumber: this.indexNumber,
indexYear: this.indexYear,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
address: this.address,
postalCode: this.city.postalCode,
name: this.city.name,
currentYearOfStudy: this.currentYearOfStudy,
})
.then((response) => {
console.log("Student inserted" + response);
addMessage({
message: "Student updated",
type: "success",
title: "STUDENT",
});
})
.catch((error) => {
addMessage({
message: "Update was not successful:" + error,
type: "danger",
title: "Update student",
});
});
},
},
};
</script>

You've postalCode and name are defined in data property without nesting them, so you could nest them to a city field when you want to send the request :
StudentService.insertStudent({
indexNumber: this.indexNumber,
indexYear: this.indexYear,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
address: this.address,
city:{
postalCode: this.postalCode,
name: this.name,
},
currentYearOfStudy: this.currentYearOfStudy
})

Related

How to loop through JSON Object in vue js

I am working on vue.js and backend is laravel. I am new to these technologies.
I am trying to display data in parent and child rows in a table base on vue material syntax.
My Laravel controlller function contains the code
$tasks = Task::select('tasks_status', DB::raw("group_concat(CONCAT('{\"id\":\"',id,'\",\"name\":\"',name,'\"}') ) as subrow"))
->where('tasks_status', '<>', "Sent Tasks")
->whereNull('user_id')
->orderBy('id', 'desc')
->groupBy('tasks_status')
->get();
I am trying to get data grouped by task_status. For each task status there are multiple rows.
My JSON is like below -
[
{
"tasks_status": "Completed Task",
"subrow": "{\"id\":\"4\",\"name\":\"d1\"}"
},
{
"tasks_status": "My Tasks",
"subrow": "{\"id\":\"2\",\"name\":\"b1\"},{\"id\":\"7\",\"name\":\"g1\"}"
}
]
Online JSON Parser validates it.
in Vue Front end I try to display this JSON data using 2 for loops Like below
<md-table v-model="searched" md-sort="name" md-sort-order="asc" md-fixed-header class="table-sort">
<md-table-toolbar>
<div class="md-toolbar-section-start">
<h1 class="md-title">Tasks</h1>
</div>
<md-field md-clearable class="md-toolbar-section-end">
<label for="Tasks">Tasks</label>
<md-select v-model="fieldsSearchTerm.searchTermForDataTable" name="search" id="search" #input="searchOnTable" >
<md-option value="">All Tasks</md-option>
<md-option value="My Tasks">My Tasks</md-option>
<md-option value="Organization Tasks"
>Organization Tasks</md-option
>
<md-option value="Received Tasks"
>Received Tasks</md-option
>
<md-option value="Completed Task"
>Completed Task</md-option
>
<md-option value="Incomplete Tasks"
>Incomplete Tasks</md-option
>
<md-option value="Sent Tasks">Sent Tasks</md-option>
</md-select>
</md-field>
<md-field md-clearable class="md-toolbar-section-end">
<b-button class="btn btn-danger modal-btn" block #click="changeStatusToDone">Done</b-button>
</md-field>
</md-table-toolbar>
<md-table-empty-state
md-label="No data found">
</md-table-empty-state>
<md-table-row slot="md-table-row" v-for="rowHeading in searched" >
<md-table-cell md-label="Task Name" md-sort-by="name">{{ rowHeading.tasks_status }}</md-table-cell>
<md-table-cell md-label="Task Status" md-sort-by="tasks_status"></md-table-cell>
<md-table-cell md-label="Due Date" md-sort-by="due_date"></md-table-cell>
<md-table-cell md-label="Priority" md-sort-by="priority"></md-table-cell>
<md-table-cell md-label="Actions" md-sort-by="">
</md-table-cell>
</md-table-row>
<md-table-row slot="md-table-row" v-for="subRowElements in rowHeading.subrow">
<md-table-cell md-label="" md-sort-by="" >
</md-table-cell>
<md-table-cell colspan=4 md-label="Task Name" md-sort-by="name">hi {{ subRowElements }}</md-table-cell>
</md-table-cell>
</md-table-row>
</md-table>
In My JS I have code like this below
import Cookies from 'js-cookie'
import axios from "axios"
import Vue from 'vue'
import VueResource from 'vue-resource'
import Form from 'vform'
const toLower = text => {
return text.toString().toLowerCase()
}
const searchByName = (items, term) => {
if (term) {
return items.filter(item => toLower(item.tasks_status).includes(toLower(term)))
}
return items
}
export default {
name: 'TableSearch',
components: {
},
data() {
form: new Form({
tasks_statusUpdate: '',
nameUpdate: '',
priorityUpdate: '',
task_descriptionUpdate: '',
dueDateUpdate: '',
taskAssignedToUserUpdate: '',
_token: Cookies.get('token')
})
return {
goods: [],
fieldsUpdate: {
tasks_statusUpdate: "",
nameUpdate: "",
priorityUpdate: "",
task_descriptionUpdate: '',
dueDateUpdate: "",
taskAssignedToUserUpdate: "",
_token: Cookies.get('token'),
},
fieldsView: {
tasks_statusView: "",
nameView: "",
priorityView: "",
task_descriptionView: '',
dueDateView: "",
taskAssignedToUserView: "",
userNameView: "",
},
fieldsTaskDone: {
tasks_status: 1,
},
fieldsSearchTerm: {
searchTermForDataTable: '',
},
fieldsCheckBox: {
cboTaskName: true,
cboTaskStatus: true,
cboDueDate: true,
cboPriority: true,
},
isOpen: true,
rows: null,
allUsersUpdate: [],
searched: [],
rowHeading:[],
subRowElements:[],
users: [
{
id: 1,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 2,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 3,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 4,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 5,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 6,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 7,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 8,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 9,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 10,
name: "Shawna vishal",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
],
rows: [],
editing_record_id: 0,
view_record_id: 0,
checkedTaskIDs: [],
dynamicColumn: [],
}
},
methods: {
newUser () {
window.alert('Noop')
},
searchOnTable () {
this.makeGetRequest();
this.searched = searchByName(this.rows, this.search)
},
fnDynamicColumns: function(e){
if (e.target.checked) {
console.log(e.target.value)
}
},
check_task_id: function(e) {
if (e.target.checked) {
console.log(e.target.value)
}
},
changeStatusToDone () {
axios
.post("api/v1/tasks/"+this.checkedTaskIDs+"/complete",
this.fieldsTaskDone
)
.then(response => {
alert("Task Done!");
})
.catch(error => {
console.log(error);
});
this.makeGetRequest();
},
async makeGetRequest() {
console.log("makeGetRequest begin ");
var fnRows = [];
await axios.get('api/v1/tasks', {
params: {
searchTermForDataTable: this.fieldsSearchTerm.searchTermForDataTable
}
})
.then((response) => {
this.rows = response.data;
fnRows = response.data;
console.log("inside axios > makeGetRequest" + JSON.stringify(this.rows));
});
this.searched = this.rows
console.log("makeGetRequest later " + this.searched);
},
async getAllUsers() {
console.log("table > getAllUsers begin ");
await axios.get('api/v1/getallusers')
.then((response) => {
this.allUsersUpdate = response.data;
});
console.log("table > outside axios user11" + this.allUsersUpdate);
},
submitUpdateForm() {
console.log(this.fieldsUpdate);
console.log(Cookies.get('token'));
axios
.put("api/v1/tasks/"+this.editing_record_id,
this.fieldsUpdate
)
.then(response => {
alert("Task Updated!");
//this.fields = {};
})
.catch(error => {
console.log(error);
});
this.makeGetRequest();
console.log("ppppnnnnnn");
},
async getTask() {
await axios.get('api/v1/tasks/'+this.editing_record_id)
.then((response) => {
this.fieldsUpdate.tasks_statusUpdate = response.data[0].tasks_status;
this.fieldsUpdate.nameUpdate = response.data[0].name;
this.fieldsUpdate.taskAssignedToUserUpdate = response.data[0].user_id;
this.fieldsUpdate.priorityUpdate = response.data[0].priority;
this.fieldsUpdate.task_descriptionUpdate = response.data[0].task_description;
if(response.data[0].due_date !== null)
{
this.fieldsUpdate.dueDateUpdate = response.data[0].due_date;
}
console.log("getTask With Join" + JSON.stringify(response.data[0]));
});
console.log("getTask With Join" + JSON.stringify(this.fieldsUpdate));
},
showUpdateModal(id) {
this.editing_record_id = id;
this.getTask();
this.$bvModal.show('taskUpdateModal')
},
softDeleteTask(id) {
if(confirm("Are you sure, you want to delete, this task?")){
axios
.delete("api/v1/tasks/"+id)
.then(response => {
alert("Task Deleted!");
//this.fields = {};
})
.catch(error => {
console.log(error);
});
this.makeGetRequest();
}
},
async getTaskForView() {
await axios.get('api/v1/tasks/'+this.view_record_id)
.then((response) => {
this.fieldsView.tasks_statusView = response.data[0].tasks_status;
this.fieldsView.nameView = response.data[0].name;
this.fieldsView.taskAssignedToUserView = response.data[0].user_id;
this.fieldsView.priorityView = response.data[0].priority;
this.fieldsView.task_descriptionView = response.data[0].task_description;
this.fieldsView.dueDateView = response.data[0].due_date;
this.fieldsView.userNameView = response.data[0].userName;
});
console.log("getTask" + JSON.stringify(this.fieldsView));
},
showViewModal(id) {
this.view_record_id = id;
this.getTaskForView();
this.$bvModal.show('taskViewModal')
},
},
created () {
console.log("inside created()1");
this.makeGetRequest();
this.getAllUsers();
console.log("outside axios" + this.rows);
enter code here
console.log("inside created() 2");
},
mounted() {
console.log("inside mounted()")
},
}
Can Anybody suggests a way to get valid JSON from controller and display it with correct loops in vue.js page. Thanks in advance.
I think you should use something like this in your Laravel controller, and then it would be easier to use loop to output json
$tasks = Task::select('tasks_status', DB::raw("group_concat(CONCAT('{\"id\":\"',id,'\",\"name\":\"',name,'\"}') ) as subrow"))
->where('tasks_status', '<>', "Sent Tasks")
->whereNull('user_id')
->orderBy('id', 'desc')
->groupBy('tasks_status')
->get()->map(function ($e) {
$e->subrow = json_decode($e->subrow);
return $e;
});

free jqGrid with Caption and without column headers

I want to display the caption, but not the column headers. When the grid is first displayed only the caption should be visible. When the grid is expanded, the column headers are visible. Please see jsFiddle
var $grid = $("#grid");
$grid.closest("div.ui-jqgrid-view")
.children("div.ui-jqgrid-hdiv")
.hide();
Here you go with a solution https://jsfiddle.net/7v70640y/5/
$("#grid").jqGrid({
colModel: [
{ name: "firstName" },
{ name: "lastName" }
],
caption: "The caption",
hiddengrid: true,
data: [
{ id: 10, firstName: "Angela", lastName: "Merkel" },
{ id: 20, firstName: "Vladimir", lastName: "Putin" },
{ id: 30, firstName: "David", lastName: "Cameron" },
{ id: 40, firstName: "Barack", lastName: "Obama" },
{ id: 50, firstName: "François", lastName: "Hollande" }
]
});
$('div[role="columnheader"]').parent().hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.14.1/css/ui.jqgrid.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.14.1/jquery.jqgrid.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css" rel="stylesheet"/>
<table id="grid"></table>
Just hide the div & it's parent div which has role as columnheader
$('div[role="columnheader"]').parent().hide();
Update with multiple jqGrid
Here you go with a solution https://jsfiddle.net/7v70640y/6/
$("#grid1").jqGrid({
colModel: [
{ name: "firstName" },
{ name: "lastName" }
],
caption: "The caption",
hiddengrid: true,
data: [
{ id: 10, firstName: "Angela", lastName: "Merkel" },
{ id: 20, firstName: "Vladimir", lastName: "Putin" },
{ id: 30, firstName: "David", lastName: "Cameron" },
{ id: 40, firstName: "Barack", lastName: "Obama" },
{ id: 50, firstName: "François", lastName: "Hollande" }
]
});
$("#grid2").jqGrid({
colModel: [
{ name: "firstName" },
{ name: "lastName" }
],
caption: "The caption",
hiddengrid: true,
data: [
{ id: 10, firstName: "Angela", lastName: "Merkel" },
{ id: 20, firstName: "Vladimir", lastName: "Putin" },
{ id: 30, firstName: "David", lastName: "Cameron" },
{ id: 40, firstName: "Barack", lastName: "Obama" },
{ id: 50, firstName: "François", lastName: "Hollande" }
]
});
$('#gview_grid1').find('div[role="columnheader"]').parent().hide();
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.14.1/css/ui.jqgrid.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.14.1/jquery.jqgrid.min.js"></script>
<table id="grid1"></table>
<br/><br/>
<table id="grid2"></table>
Hope this will help you.

Conditional and custom validation on Add / Edit form fields when using Kendo grid custom popup editor template

I am using a custom template for kendo grid popup Add / Edit form. Here is my working DEMO
I want to implement conditional validation on form fields such as if any value is entered for Address (not left empty) then the fields City and Postal Code should become required, otherwise they can be empty. Also I want to ise a custom validation rule for PostCode so that its length should always be equal to 4 else it should show a custom error message as "Postcode must be four digits"
I have referred these links:
Validation rules in datasource.model
Custom validation rules and error messages
but I can't figure out how can I implement validations in my datasource model?
Here is my code:
HTML:
<h3>I want to implement conditional validation on Add/Edit form such as if any value is entered for Address then the fields City and Postal Code should become required</h3>
<div id="grid"></div>
<script id="popup-editor" type="text/x-kendo-template">
<p>
<label>Name:<input name="name" required /></label>
</p>
<p>
<label>Age: <input data-role="numerictextbox" name="age" required /></label>
</p>
<p>
<label>Address: <input name="address"/></label>
</p>
<p>
<label>City: <input name="city"/></label>
</p>
<p>
<label>Post Code: <input name="postcode"/></label>
</p>
</script>
JS:
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" },
{ command: "edit" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: { id: "id" },
fields: {
name:{},
age:{},
address:{},
city:{},
postcode:{},
},
}
},
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html())
},
toolbar: [{ name: 'create', text: 'Add' }]
});
If i were to do that, i would do these approach where
I will create a custom validator
Override the edit(grid) function place the validator there
Override the save(grid) function use validator.validate() before saving
Here is an example in dojo
basically this is the grid code:
var validator;
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" },
{ command: "edit" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: { id: "id" },
fields: {
name:{},
age:{},
address:{},
city:{},
postcode:{},
},
}
},
save: function(e) {
if(!validator.data("kendoValidator").validate()){
e.preventDefault();
}
},
edit: function(){
validator = $("#test-form").kendoValidator({
validateOnBlur: false,
rules: {
matches: function(input) {
var requiredIfNotNull = input.data('test');
// if the `data-test attribute was found`
if (requiredIfNotNull) {
// get the input requiredIfNotNull
var isFilled = $(requiredIfNotNull);
// trim the values and check them
if ( $.trim(isFilled.val()) !== "" ) {
if($.trim(input.val()) !== ""){
// the fields match
return true;
}else{
return false;
}
}
// don't perform any match validation on the input since the requiredIf
return true;
}
// don't perform any match validation on the input
return true;
}
},
messages: {
email: "That does not appear to be a valid email address",
matches: function(input) {
return input.data("testMsg");
}
}
});
},
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html())
},
toolbar: [{ name: 'create', text: 'Add' }]
});
ps: i used to many if statement, you could simplify it i think
Here is the DEMO how I implemented it:
HTML:
<div id="grid"></div>
<script id="popup-editor" type="text/x-kendo-template">
<div id="myForm">
<p>
<label>Name:<input name="name" required /></label>
</p>
<p>
<label>Age: <input data-role="numerictextbox" name="age" required /></label>
</p>
<p>
<label>Address: <input name="address" id="address"/></label>
</p>
<p>
<label>City: <input name="city" id="city"/></label>
</p>
<p>
<label>Post Code: <input name="postcode" id="postcode"/></label>
<!--<span class="k-invalid-msg" data-for="postcode"></span>-->
</p>
</div>
</script>
JS:
var validator;
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" },
{ field: "address" },
{ field: "city" },
{ field: "postcode" },
{ command: "edit" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30, address:'Addr', city:"city", postcode: '1234' },
{ id: 2, name: "John Doe", age: 33, address:'Addr11', city:"city11", postcode: '4321' }
],
schema: {
model: { id: "id" },
fields: {
name:{},
age:{},
address:{},
city:{},
postcode:{},
},
}
},
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html())
},
toolbar: [{ name: 'create', text: 'Add' }],
save: function(e) {//alert('save clicked');
if(!validator.validate()) {
e.preventDefault();
}
},
edit: function(e){
//alert('edit clicked');
validator = $("#myForm").kendoValidator({
messages: {
postcode: "Please enter a four digit Postal Code"
},
rules: {
postcode: function(input) {
//console.log(input);
if (input.is("[name='address']"))
{
if (input.val() != '')
{
$('#city, #postcode').attr('required', 'required');
//return false;
}
else
{
$('#city, #postcode').removeAttr("required");
}
}
else if (input.is("[name='postcode']")) {
if ($('#address').val() != '' && input.val().length != 4)
return false;
}
return true;
}
},
}).data("kendoValidator");
},
});

kendoAutoComplete shows [object object] when clicked on template or item

This code return the result below in snaps.
How to populate text field with FirstName and LastName when click on template instead of [object object] ?
function forAutoComplete(FieldName){
var autoCompleteUsers = $("#employees").kendoAutoComplete({
minLength: 1,
dataTextField: FieldName,
template: '<div style="border-bottom: 1px solid DARKGRAY; padding:10px 0; clear:both;">' +
'<img style="float:left; margin-right:20px;" width=\"127\" height=\"127\" src=\"<?php echo base_url() ?>/user_uploads/employee_images/${data.Photo}\" alt=\"${data.Photo}\"/>'+
'<div style="display: inline-block;"><p>${ data.FileNo}</p>' +
'<h3>${ data.FirstName } ${ data.LastName }</h3></div>'+
'<div style="clear: both; "></div></div>',
dataSource: {
serverFiltering: true,
transport: {
read: {
type: "GET",
dataType: "json",
contentType:'application/json; charset=utf-8',
url: "<?php echo base_url() ?>index.php/hr_management/manage_hr/search_employee/",
data: function (arg){
return {FieldName : autoCompleteUsers.data("kendoAutoComplete").value()};
}
}
}
},
height: 300,
change: onChangeAutoComplete
});
}
The problem is likely to be related with the value that you set for dataTextField.
Doing some-sort-of-reverse-engineering, I guess that the JSON data that you return is something like:
[
{data: { FileNo: "0001", FirstName: "OnaBai", LastName: "it's me", Photo: "https://si0.twimg.com/profile_images/2648375258/7f7e451f0de1eb467fe35f4f481d7bf7_bigger.jpeg" } },
{data: { FileNo: "0002", FirstName: "Burke", LastName: "Holland", Photo: "https://si0.twimg.com/profile_images/3342899483/51e933d69222ce8ad8cd14e655116959.jpeg" } },
{data: { FileNo: "0003", FirstName: "Todd", LastName: "Anglin", Photo: "https://si0.twimg.com/profile_images/1478082886/todd-anglin-close-up_illustrated.png" } }
]
If so, you should be defining it as data.FirstName.
If you are defining it as:
[
{ FileNo: "0001", FirstName: "OnaBai", LastName: "it's me", Photo: "https://si0.twimg.com/profile_images/2648375258/7f7e451f0de1eb467fe35f4f481d7bf7_bigger.jpeg" },
{ FileNo: "0002", FirstName: "Burke", LastName: "Holland", Photo: "https://si0.twimg.com/profile_images/3342899483/51e933d69222ce8ad8cd14e655116959.jpeg" },
{ FileNo: "0003", FirstName: "Todd", LastName: "Anglin", Photo: "https://si0.twimg.com/profile_images/1478082886/todd-anglin-close-up_illustrated.png" }
]
Then it should be just FirstName.
Example of the first approach in here while second in here
If you define dataTextField: "data", and use the first approach for your JSON then you get the [object Object]. See it here

Jquery email validation of email and one specific message

I have a jquery syntax as below
Email: {
required: true,
email: true,
remote: {
url: "emails.php",
type: "post",
},
which validate a field as below;
<td class="field" style="width: 246px">
<input id="Email" name="Email" type="text" value="<?php echo $email; ?>" style="width: 246px">
</td>
<td class="status"></td>
which displays a success/error message in <td class="status">
It validate the data when a valid email ID is entered.
The ajax callback is a simple true/false data.
What i want is, it should also validate when a specific message "NA" is entered in the field. Is this possible??
Here is the complete javascript;
<script id="demo" type="text/javascript">
$.noConflict();
jQuery(document).ready(function($) {
var validator = $("#signupform").validate({
rules: {
ID: "required",
Name: {
required: true,
minlength: 5,
},
Address: "required",
Dept: "required",
Phone: "required",
College: "required",
LDate: "required",
EDate: "required",
Year: "required",
Privilage: "required",
username: {
required: true,
minlength: 5,
},
Email: {
required: true,
email: true,
remote: {
url: "emails.php",
type: "post",
},
},
LibID: {
required: true,
},
},
messages: {
ID: "Enter ID",
Name: "Enter Name",
Address: "Enter Address",
Phone: "Enter Phone Number",
College: "Specify College",
LDate: "Enter Licenseing Date",
EDate: "Specify License Expiry Date",
Year: "Specify Year",
Dept: "Specify Department",
Privilage: "Specify Privilage",
username: {
required: "Enter a username",
minlength: jQuery.format("Enter at least {0} characters"),
remote: jQuery.format("username not available")
},
Email: {
required: "Enter a valid email address",
minlength: "Enter a valid email address",
remote: jQuery.format("already registered"),
},
LibID: {
required: "Enter a Library ID",
minlength: "Enter a Library ID",
remote: jQuery.format("ID is already in use"),
},
},
errorPlacement: function(error, element) {
error.appendTo( element.parent().next() );
},
success: function(label) {
label.html("OK").addClass("checked");
}
});
$('.username').alphanumeric({nocaps:true}).alphanumeric({ichars:'._'});
});
</script>
Thanks in advance :)
blasteralfred.
I assume you are using the jquery.validation plugin.
If thats the case you can use depends with email rule:
Email: {
required: true,
email: {
depends: function(element){
return element.value != "NA";
}
},
remote: {
url: "emails.php",
type: "post",
},
}

Resources