I have made and AngularJs app and made Form in HTML/CSS. The form takes 2 Dates. StartDate and endDate. For validations, I used the AngularJs Ng-messages. I created a custom validation function to check that endDate should not be before startDate. But the function is not invoking. Things i have checked.
Include Ng-messages file in start.
Add the function to Scope.
add the customer function name in input Tag of HTML.
Checked the spelling issue.
But nothing has worked for me. So, here I am to show it to you guys.
Layout = null;
}
<form name="newTenatForm" class="flex-fill" ng-submit="newTenatForm.$valid && onAddEditTenantSubmitForm(newTenatForm)" novalidate>
<div class="row">
<div class="col-lg-6 offset-lg-3">
<div class="card mb-0">
<div class="card-body">
<div class="text-center mb-3">
<i class="icon-stack icon-2x text-success border-success border-3 rounded-round p-3 mb-3 mt-1"></i>
<h5 class="mb-0">#ViewBag.title</h5>
<span class="d-block text-muted">Fields with * are required</span>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-group-feedback form-group-feedback-right">
<input type="text" class="form-control" placeholder="Name *" name="tenantName" ng-minlength="5" ng-model="state.tenantModel.name" required>
<ng-messages class="form-text text-danger-400"
ng-if="newTenatForm.$submitted || newTenatForm.tenantName.$touched"
for="newTenatForm.tenantName.$error">
<div ng-message="minlength">Tenant name is too short.</div>
<div ng-message="required">Tenant name is required</div>
</ng-messages>
<div class="form-control-feedback">
<i class="icon-user-check text-muted"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-group-feedback form-group-feedback-right">
<input type="text" class="form-control" placeholder="Identifier *" name="tenantIdentifier" ng-minlength="5" ng-model="state.tenantModel.identifier" required>
<ng-messages class="form-text text-danger-400"
ng-if="newTenatForm.$submitted || newTenatForm.tenantIdentifier.$touched"
for="newTenatForm.tenantIdentifier.$error">
<div ng-message="minlength">Tenant Identifier is too short.</div>
<div ng-message="required">Tenant identifier is required</div>
</ng-messages>
<div class="form-control-feedback">
<i class="icon-user-check text-muted"></i>
</div>
</div>
</div>
</div>
<div class="form-group form-group-feedback form-group-feedback-right">
<input type="text" class="form-control" placeholder="Connection String" ng-model="state.tenantModel.connectionString">
<div class="form-control-feedback">
<i class="icon-user-plus text-muted"></i>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-group-feedback form-group-feedback-right">
<input type="date" class="form-control" placeholder="Start Date" id="anytime-date" name="tenantStartDate" ng-model="state.tenantModel.startFrom" required>
<ng-messages class="form-text text-danger-400"
ng-if="newTenatForm.$submitted || newTenatForm.tenantStartDate.$touched"
for="newTenatForm.tenantStartDate.$error">
<div ng-message="required">Tenant start date is required</div>
</ng-messages>
<div class="form-control-feedback">
<i class="icon-user-lock text-muted"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-group-feedback form-group-feedback-right">
<input type="date" class="form-control" placeholder="End Date" id="tenantEndDate" name="tenantEndDate" ng-model="state.tenantModel.endOn" required compareWithStartDate>
<ng-messages class="form-text text-danger-400"
ng-if="newTenatForm.$submitted || newTenatForm.tenantEndDate.$touched"
for="newTenatForm.tenantEndDate.$error">
<div ng-message="required">Tenant end date is required</div>
<div ng-message="checkEndDate">End date cannot be before start date.</div>
</ng-messages>
<div class="form-control-feedback">
<i class="icon-user-lock text-muted"></i>
</div>
</div>
</div>
</div>
<div class="form-group form-group-feedback form-group-feedback-right">
<div class="form-group row">
<label class="col-form-label col-lg-2">Tenant Type *</label>
<div class="col-lg-10">
<select class="form-control" id="tenantType" name="tenantType" ng-model="state.tenantModel.tenantType" required>
<option value="1">Trial</option>
<option value="2">Standard</option>
</select>
<ng-messages class="form-text text-danger-400"
ng-if="newTenatForm.$submitted || newTenatForm.tenantType.$touched"
for="newTenatForm.tenantType.$error">
<div ng-message="required">Pleas select tenant type.</div>
</ng-messages>
</div>
</div>
</div>
<button type="submit" value="Submit" class="btn bg-teal-400 btn-labeled btn-labeled-right"><b><i class="icon-plus3"></i></b> #if (ViewBag.title == "Update Tenant")
{<span>Update Acccount</span> }
else
{ <span>Create account </span>} </button>
</div>
</div>
</div>
</div>
</form>```
and this is Js code.
```(function () {
var app = angular.module('app');
app.controller('MultiTenantController', ['$scope', '$window', '$filter', 'TenantServices', function ($scope, $window, $filter, TenantServices) {
var objectA = {}
var state = {
tenantModel: {
addedOn: '',
connectionString: '',
createdBy: '',
endOn: '',
id: '',
identifier: '',
isDisabled: '',
items: [{
isDisabled: '',
tenantType: '',
endOn: '',
startFrom: '',
}],
name: '',
startFrom: '',
tenantType: '',
userId: '',
},
};
var init = function (id) {
if (id) { tenantEdit(id); };
$(document).ready(function () {
tenantTable = $('#table_Tenants').DataTable({
ajax: {
url: 'API/MultiTenant/Pagged',
method: 'POST'
},
columns: [
{ data: 'name' },
{ data: 'identifier' },
{ data: 'connectionString' },
{
data: 'startFrom',
render: function (startFrom) {
return $filter('date')(startFrom, 'medium');
}
},
{
data: 'addedOn',
render: function (addedOn) {
return $filter('date')(addedOn, 'medium');
}
},
{
data: 'endOn',
render: function (endOn) {
return $filter('date')(endOn, 'medium');
}
},
{
data: 'isDisabled',
render: function (isDisabled) {
return !isDisabled ?'<span class="badge badge-success">Active</span>':'<span class="badge badge-danger">Inactive</span>';
}
},
{
data: function (data) {
return data;
},
orderable: false,
render: function (data) {
return `<div class="list-icons">
<div class="dropdown">
<a href="#" class="list-icons-item" data-toggle="dropdown">
<i class="icon-menu9"></i>
</a>
<div class="dropdown-menu dropdown-menu-right">
<i class="icon-database-upload"></i>Create Database
<i class="icon-database-edit2"></i>Edit
<i class="icon-database-remove"></i>Delete
</div>
</div>
</div>`;
}
},
]
});
tenantTable.on('click', '.createTenantDatabase', function () {
const $row = $(this).closest('tr');
const rowData = tenantTable.row($row).data();
addTenantDatabase(rowData);
});
tenantTable.on('click', '.deleteTenant', function () {
const $row = $(this).closest('tr');
const rowData = tenantTable.row($row).data();
deleteTenant(rowData);
});
})
};
const onAddEditTenantSubmitForm = function (newTenatForm) {
if (!state.tenantModel.userId) {
addTenant(newTenatForm);
}
else {
updateTenant(newTenatForm);
}
};
var addTenant = function (newTenatForm) {
state.isLoading = true;
TenantServices.addTenant(state.tenantModel).then(
function () {
swalInit.fire({
title: 'Success',
text: 'Tenant has been created',
type: 'success'
});
},
function (errorResponse) {
if (errorResponse.status === 400) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while adding tenant.',
type: 'error 400'
});
}
else if (errorResponse.status === 500) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while adding tenant.',
type: 'error 500'
});
}
}
)
.finally(() => state.isLoading = false);
};
var addTenantDatabase = function (rowObj) {
state.isLoading = true;
TenantServices.createTenantDatabase(rowObj.i).then(
function () {
swalInit.fire({
title: 'Success',
text: 'Tenant Database has been created',
type: 'success'
});
table_Tenants.ajax.reload();
},
function (errorResponse) {
if (errorResponse.status === 400) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while creating database tenant.',
type: 'error 400'
});
}
else if (errorResponse.status === 500) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while creating database tenant.',
type: 'error 500'
});
}
}
)
.finally(() => state.isLoading = false);
};
var updateTenant = function (rowObj) {
state.isLoading = true;
TenantServices.updateTenant(state.tenantModel).then(
function () {
swalInit.fire({
title: 'Success',
text: 'Tenant Updated!',
type: 'success'
});
tenantTable.ajax.reload();
},
function (errorResponse) {
if (errorResponse.status === 500) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while Updating Tenant.',
type: 'error'
});
}
else if (errorResponse.status === 404) {
swalInit.fire({
title: 'Server Error',
text: 'Tenant not found on Server.',
type: 'error'
});
}
}
)
.finally(() => state.isLoading = false);
};
var deleteTenant = function (rowObj) {
state.isLoading = true;
TenantServices.deleteTenant(rowObj.id).then(
function () {
swalInit.fire({
title: 'Success',
text: 'Tenant Deleted!',
type: 'success'
});
tenantTable.ajax.reload();
},
function (errorResponse) {
if (errorResponse.status === 500) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while Deleting Tenant.',
type: 'error'
});
}
else if (errorResponse.status === 404) {
swalInit.fire({
title: 'Server Error',
text: 'Tenant not found on Server.',
type: 'error'
});
}
}
)
.finally(() => state.isLoading = false);
};
var tenantEdit = function (id) {
TenantServices.getTenantById(id).then(function (data) {
var startDate = new Date(data.found.startFrom + "Z");
var endDate = new Date(data.found.endOn + "Z");
state.tenantModel = data.found;
state.tenantModel.startFrom = startDate;
state.tenantModel.endOn = endDate;
if(state.tenantModel.tenantType == 1)
{
$(function () {
$('#tenantType').val('1');
});
} else if (state.tenantModel.tenantType == 2)
{
$(function () {
$('#tenantType').val('2');
});
}
});
};
var compareWithStartDate = function () {
if (state.tenantModel.startFrom == state.tenantModel.endOn) {
newTenatForm.tenantEndDate.$setValidity('checkEndDate', true);
}
else {
newTenatForm.tenantEndDate.$setValidity('checkEndDate', false);
}
};
$scope.onAddEditTenantSubmitForm = onAddEditTenantSubmitForm;
$scope.tenantEdit = tenantEdit;
$scope.compareWithStartDate = compareWithStartDate;
$scope.state = state;
$scope.init = init;
}]);
})();```
My mistake here was not making the directive for the custom validation.
Related
So I have a dropzone file uploader. each successfull upload returns the following
File: {
"upload": {
"uuid": "f89f409b-7e49-4503-98d8-dc060e75b874",
"progress": 0,
"total": 5017004,
"bytesSent": 0,
"filename": "20190902_115950.jpg"
},
"status": "error",
"previewElement": {},
"previewTemplate": {},
"accepted": false,
"dataURL": "data:image/jpeg;base64,/9j/4XGiRXh/WU8GGXVL5BHN5PW...",
"width": 3024,
"height": 4032
}
I have a laravel backend with a request validation for this:
rules = [
...
'featured_image' => 'image',
]
However, my laravel backend returns that the featured image field must be an image. So I'm not sure what format the backend expects.
My dropzone component looks like this:
<template>
<div
class="dropzone mb-3 dz-clickable"
:class="[multiple ? 'dropzone-multiple' : 'dropzone-single']"
>
<div class="fallback">
<div class="custom-file">
<input
type="file"
class="custom-file-input"
id="projectCoverUploads"
:multiple="multiple"
/>
<label class="custom-file-label" for="projectCoverUploads"
>Choose file</label
>
</div>
</div>
<div
class="dz-preview dz-preview-single"
v-if="!multiple"
:class="previewClasses"
ref="previewSingle"
>
<div class="dz-preview-cover">
<img class="dz-preview-img" data-dz-thumbnail />
</div>
</div>
<ul
v-else
class="dz-preview dz-preview-multiple list-group list-group-lg list-group-flush"
:class="previewClasses"
ref="previewMultiple"
>
<li class="list-group-item px-0">
<div class="row align-items-center">
<div class="col-auto">
<div class="avatar">
<img class="avatar-img rounded" data-dz-thumbnail />
</div>
</div>
<div class="col ml--3">
<h4 class="mb-1" data-dz-name>...</h4>
<p class="small text-muted mb-0" data-dz-size>...</p>
</div>
<div class="col-auto">
<button data-dz-remove="true" class="btn btn-danger btn-sm">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "dropzone-file-upload",
props: {
options: {
type: Object,
default: () => ({}),
},
value: [String, Object, Array],
url: {
type: String,
default: "http://",
},
multiple: Boolean,
previewClasses: [String, Object, Array],
},
model: {
prop: "value",
event: "change",
},
data() {
return {
currentFile: null,
files: [],
showList: false,
};
},
methods: {
async initDropzone() {
let Dropzone = await import("dropzone");
Dropzone = Dropzone.default || Dropzone;
Dropzone.autoDiscover = false;
let preview = this.multiple
? this.$refs.previewMultiple
: this.$refs.previewSingle;
let self = this;
let finalOptions = {
...this.options,
url: this.url,
thumbnailWidth: null,
thumbnailHeight: null,
previewsContainer: preview,
previewTemplate: preview.innerHTML,
maxFiles: !this.multiple ? 1 : null,
acceptedFiles: !this.multiple ? "image/*" : null,
init: function () {
this.on("addedfile", function (file) {
if (!self.multiple && self.currentFile) {
// this.removeFile(this.currentFile);
}
self.currentFile = file;
});
},
};
this.dropzone = new Dropzone(this.$el, finalOptions);
preview.innerHTML = "";
let evtList = [
"drop",
"dragstart",
"dragend",
"dragenter",
"dragover",
"addedfile",
"removedfile",
"thumbnail",
"error",
"processing",
"uploadprogress",
"sending",
"success",
"complete",
"canceled",
"maxfilesreached",
"maxfilesexceeded",
"processingmultiple",
"sendingmultiple",
"successmultiple",
"completemultiple",
"canceledmultiple",
"totaluploadprogress",
"reset",
"queuecomplete",
];
evtList.forEach((evt) => {
this.dropzone.on(evt, (data) => {
this.$emit(evt, data);
if (evt === "addedfile") {
this.files.push(data);
this.$emit("change", this.files);
} else if (evt === "removedfile") {
let index = this.files.findIndex(
(f) => f.upload.uuid === data.upload.uuid
);
if (index !== -1) {
this.files.splice(index, 1);
}
this.$emit("change", this.files);
}
});
});
},
},
async mounted() {
this.initDropzone();
},
};
</script>
<style></style>
As you can see below, I have a modal that should be validated then send a request to the server. The problem is that if I try to submit for the first time, that validation is worked properly but for the second time it won't work. When I debug the codes I found out that validationCheck() worked fine but the resolve() doesn't return any result to the add() in certificate-manager file.
request.js
let insert = function (isPost = false, url, data, reloadLocation = false, table = null,
modal = null, ponds) {
let request = null;
if (isPost) {
let uploadNotify = uploadNotification();
//step 3
let config = {
onUploadProgress: function (progressEvent) {
let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(percentCompleted);
uploadNotify.update('message', '<strong>Uploading</strong> ' + percentCompleted + ' %');
uploadNotify.update('progress', percentCompleted);
},
headers: {
'content-type': 'multipart/form-data'
}
};
//step 4
request = axios.post(url, data, config)
} else {
//step 4
request = axios.get(url, {
params: data
});
}
request.then(function (response) {
console.log(response);
let data = response['data'];
if (data['status'] === 200) {
let content = {
'title': 'Done!',
'message': data['message']
};
notification(content, 1);
if (reloadLocation)
location.reload();
if (table) {
table.ajax.reload();
clearModal('.inp', ponds);
}
}
})
.catch(function (error) {
console.log(error);
let data = error['data'];
let content = {
'title': 'Error!',
'message': data['message']
};
notification(content, 0);
})
.then(function () {
if (modal)
closeModal(modal);
});
};
utilities.js
async function validationCheck (id, rules) {
jQuery.validator.addMethod('passwordCheck', function (value, element, param) {
//Your Validation Here
let oldPass = jQuery('#input-old-password').val();
let confirmPass = jQuery('#input-confirm-password').val();
return oldPass != null && confirmPass === value;
// return bool here if valid or not.
}, 'Your error message!');
jQuery.validator.addMethod('phoneNumber', function (value, element, param) {
value = value.replace(/\s+/g, "");
return this.optional(element) || value.length > 9 &&
value.match(/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/);
}, 'Please specify a valid phone number');
jQuery.validator.addMethod('startDate', function (value, element, param) {
return (parseInt(value) > 2000)
}, 'Please specify a valid year');
jQuery.validator.addMethod('endDate', function (value, element, param) {
return (parseInt(value) >= parseInt(jQuery('#input-start-time').val()) ||
jQuery('#input-current').is(":checked"))
}, 'Please specify a valid year');
jQuery.validator.addMethod('uendDate', function (value, element, param) {
return (parseInt(value) >= parseInt(jQuery('#input-update-start-time').val()) ||
jQuery('#input-update-current').is(":checked"))
}, 'Please specify a valid year');
return new Promise((resolve, reject)=> {
jQuery(id).validate({
// define validation rules
rules: rules,
errorPlacement: function (error, element) {
let group = element.closest('.input-group');
if (group.length) {
group.after(error.addClass('invalid-feedback'));
} else {
element.after(error.addClass('invalid-feedback'));
}
},
// messages: {
// username: {
// required: "Username is required"
// }
// },
//display error alert on form submit
invalidHandler: function (event, validator) {
// let alert = jQuery('#kt_form_1_msg');
// alert.removeClass('kt--hide').show();
KTUtil.scrollTo(id, -200);
reject(false);
},
submitHandler: function (form) {
resolve(true);
//form[0].submit(); // submit the form
}
});
});
}
certificate-manager.js
let add = async function () {
let check = await validationCheck("#form", {
title: {
required: true
},
company: {
required: true
},
start: {
required: true,
date: true,
digits: true,
minlength: 4,
maxlength: 4,
startDate: true
},
end: {
date: true,
digits: true,
minlength: 4,
maxlength: 4,
endDate: true
},
description: {
required: true
}
}).then(value => {
console.log(value)
insert(
false,
'/api/add/certificate',
getInputsData(),
false,
table,
"#kt_modal")
}, reason => {
console.log(reason)
}).catch(reason => {
console.log(reason)
});
}
<!--begin:: insert Modal-->
<div class="modal fade" id="kt_modal" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New Certificate</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
</button>
</div>
<div class="modal-body">
<form id="form">
<div class="row">
<div class="col-12">
<div class="form-group">
<label for="input-title"
class="form-control-label">Title</label>
<input type="text" class="inp form-control"
name="title"
id="input-title">
</div>
<div class="form-group">
<label for="input-company-institute"
class="form-control-label">Company/Institute</label>
<input type="text" class="inp form-control" name="company" id="input-company-institute">
</div>
<div class="row">
<div class="form-group col-6">
<label for="input-start-time"
class="form-control-label">From Year</label>
<input type="text" class="inp form-control" name="start" id="input-start-time">
</div>
<div class="form-group col-6">
<label for="input-end-time"
class="form-control-label">To Year</label>
<input type="text" class="inp form-control" name="end" id="input-end-time">
<div class="mt-2">
<label for="input-current" class="kt-checkbox kt-checkbox--brand col-6">
<input type="checkbox" id="input-current"> Current
<span></span>
</label>
</div>
</div>
</div>
<div class="form-group">
<label for="input-description"
class="form-control-label">Description</label>
<textarea class="inp form-control" name = "description" id="input-description"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="add-btn" onclick="add()" type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!--end::insert Modal-->
the order of the files is:
'../../../assets/adminPanel/js/utilities.js',
'../../../assets/adminPanel/js/request.js',
'../../../assets/adminPanel/js/pages/resume/certificate-manager.js'
I'm starting with vue.js and firebase and I have a chat system using firebase. I get all the users’ id that have sent messages to me. So in my database I get their data and list with a v-for.
After listing them I get their messages from FB to list in a message box below each user.
Everything is working fine but I cannot get sent messages instantly after sending them.
I made a workaround with push() to append each sent message to data property but I'd like to know if there is a better way to do that with vue.js.
I've tested with plain javascript (separately with one message box) and the chat is updated on every sent message.
Is there a way to make this work without replacing all data object or calling all the listing process again? I tried with Vue's Reactivity but I could not make it work as expected.
<div v-if="isLoading == true" id="loading"><img class="loading" src="../assets/img/loading.gif" /></div>
<div v-if="isLoading == false" class="row messages-row" v-for="(item, index) in memberData" :key="index">
<div class="col-md-4 col-12">
<div class="messages-profile-infos">
<div class="messages-profile-infos-img img-fluid" v-bind:style="{'background-image': 'url(http://localhost/backend/imgs/'+item.memberProfileImg + ')' }"></div>
<div class="messages-profile-infos-text">
<p>{{ item.memberName }} {{ item.memberLastname }}</p>
<p>{{ item.memberCity }} - {{ item.memberState }}</p>
</div>
</div>
</div>
<div class="col-md-2 col-12">
<div class="messages-btns">
<button class="btn trade-btn" #click="showConversation(item.memberID)">Messages</button>
</div>
</div>
<div class="col-md-6 col-12">
<div class="messages-status">
<a class="btn border btn-circle text-uppercase confirm-service-btn" href="javascript:void(0);">
Confirm
</a>
<a class="btn border btn-circle text-uppercase cancel-service-btn" href="javascript:void(0);">Cancel</a>
</div>
</div>
<!-- conversation box -->
<div v-if="memberBox == item.memberID" class="conversation-container" :id="item.memberID">
<div v-for="(tour, index) in item.tours" :key="index" id="tourOnConversation" class="tourOnConversation">
<span>Tour:</span>
<span><strong>{{ tour.title }}</strong></span>
</div>
<div id="messages-container" class="messages-container" :key="item.memberID">
<div v-for="message in item.messages" class="d-flex" :class="[message.uid != myID ?'justify-content-start':'justify-content-end']">
<span class="badge badge-pill" :class="[message.uid != myID ?'badge-primary':'badge-secondary']">{{ message.message }}</span>
</div>
</div>
<div class="message-typing-container">
<form id="messages_form" action="" method="POST">
<div class="typing-container">
<input id="message" v-model="messages" type="text" class="message-typing" autocomplete="off" />
<input class="send-message" type="submit" value="Send" #click="sendMessage(item.memberID, item.tour)" />
</div>
</form>
</div>
</div>
<hr />
</div>
var firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxxxx",
databaseURL: "xxxxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
};
firebase.initializeApp(firebaseConfig);
let app = new Vue({
el: "#app",
data() {
return {
memberData: {},
myMessages: [],
memberMessages: [],
myID: userID,
messages: "",
messageBox: 0,
conversation: {},
isLoading: true,
memberBox: 0,
};
},
created: function () {
this.getAllMessages();
},
methods: {
scrollBox: function () {
let messagebox = document.querySelector("#messages-container");
messagebox.scrollTop = messagebox.scrollHeight;
},
getAllMessages: function () {
let distinct = "";
firebase
.firestore()
.collection("messages")
.where("memberID", "==", `${this.myID}`)
.orderBy("date")
.onSnapshot((res) => {
let members = [];
res.forEach((doc) => {
members.push(doc.data().uid);
});
distinct = Array.from(new Set(members));
this.getUserToTalk(distinct);
});
},
getMyMessages: function (memberID) {
let myMessages = [];
firebase
.firestore()
.collection("messages")
.where("uid", "==", `${this.myID}`)
.where("memberID", "==", `${memberID}`)
.orderBy("date")
.onSnapshot((res) => {
res.forEach((doc) => {
myMessages.push(doc.data());
});
});
return myMessages;
},
getMessages: function (memberID) {
let messages = [];
firebase
.firestore()
.collection("messages")
.where("uid", "==", `${memberID}`)
.where("memberID", "==", `${this.myID}`)
.orderBy("date")
.onSnapshot((res) => {
res.forEach((doc) => {
messages.push(doc.data());
});
});
return messages;
},
getUserToTalk: function (memberID) {
axios
.post("http://localhost/backend/getMemberToTalk.php", {
token: token,
whoToTalkTo: memberID,
})
.then((response) => {
// console.log(response.data);
if (response.data != "Error receiving data") {
let joinedData = [];
response.data.forEach((res) => {
let messages = this.getMessages(res.memberID);
let myMessages = this.getMyMessages(res.memberID);
// console.log(messages);
// console.log(myMessages);
let conversation = [];
let data = {};
setTimeout(() => {
conversation = [...messages, ...myMessages];
conversation.sort(function (a, b) {
return a.date - b.date;
});
// console.log(conversation);
if (conversation.length > 0) {
data = {
memberID: res.memberID,
memberProfileImg: res.memberProfileImg,
memberName: res.memberName,
memberLastname: res.memberLastname,
memberCity: res.memberCity,
memberState: res.memberState,
messages: conversation,
tour: conversation[0].tour,
};
this.isLoading = false;
} else {
this.isLoading = true;
this.getAllMessages();
}
joinedData.push(data);
}, 2000);
});
// console.log(joinedData);
this.memberData = joinedData;
console.log(this.memberData);
} else {
console.log(response.data);
}
})
.catch((error) => {
console.log(error);
});
},
sendMessage: function (memberID, tourID) {
$("#messages_form").on("submit", (e) => {
e.preventDefault();
let message = this.messages;
if (!message.trim()) return;
let postmessage = {
uid: JSON.stringify(this.myID),
memberID: JSON.stringify(memberID),
message: message,
date: Date.now(),
tour: "2",
};
// console.log(message);
this.messages = "";
this.memberData.forEach((res) => {
console.log(res.messages);
if (memberID == res.memberID) res.messages.push(postmessage);
});
console.log(this.memberData);
firebase.firestore().collection('messages').add({
uid: JSON.stringify(this.myID),
memberID: JSON.stringify(memberID),
message: message,
date: Date.now(),
tour: tourID
}).then(res => {
// console.log('Message sent: ' + res.message);
}).catch(e => console.log(e));
});
},
showConversation: function (memberID) {
// console.log(memberID);
// let id = $('.conversation-container').attr('id');
this.memberBox = memberID;
if (this.memberBox == memberID) {
$(".conversation-container").toggle("fast");
}
},
},
mounted() {},
});
I want to be displayed the toastr popup message when the user try to insert the duplicate value for BageCode in form the if anyone can help me it will be so kind of him.
I the rest form column validation is working the toaster is working but I don't know how to compare the data from database and data in form
like this
if (this.form.BadgeCode == data.BadgeCode) {
toast.fire({
type: "warning",
title: "The badge code has already been taken."
});
}
Code in EmployeeController is:
public function index()
{
$date=\Carbon\Carbon::today();
// $this->authorize('isAdmin');
$employee=Employee::where('expiredate','>',$date)->paginate(5);
// return Employee::all();
return response()->json($employee);
}
public function store(Request $request)
{
// $this->authorize('isAdmin');
$this->validate($request,[
// 'BadgeCode'=>'required|string',
'BadgeCode'=>'required|unique:employees,BadgeCode',
'BadgeType'=>'required',
]) 'company_id'=>'required',
}
Code in api route is:
Route::apiResources(['employee'=>'API\EmployeeController']);
Code in Employee.vue is:
<div
style="width:45%;margin-left: 35%;"
class="modal fade"
id="addNew"
tabindex="-1"
role="dialog"
aria-labelledby="addNewLabel"
aria-hidden="true"
>
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-show="!editMode" id="addNewLabel">Add New employee</h5>
<h5 class="modal-title" v-show="editMode" id="addNewLabel">Update employee's Info</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form
#submit.prevent="editMode ? updateemployee() : createemployee()"
enctype="multipart/form-data"
>
<div class="modal-body">
<div class="form-group">
<select
name="company_id"
id="company_id"
:class="{'is-invalid':form.errors.has('company_id')}"
class="form-control"
v-model="form.company_id"
>
<option value selected>Select Company</option>
<option
v-for="Company in Companies"
:key="Company.id"
:value="Company.id"
>{{Company.Company}}</option>
</select>
<has-error :form="form" field="company_id"></has-error>
</div>
<div class="form-group">
<input
v-model="form.BadgeCode"
placeholder="Enter BadgeCode"
type="text"
name="BadgeCode"
class="form-control"
/>
<!-- :class="{ 'is-invalid': form.errors.has('BadgeCode') }" -->
<!-- <has-error :form="form" field="BadgeCode"></has-error> -->
</div>
<div class="form-group">
<select
name="BadgeType"
v-model="form.BadgeType"
id="BadgeType"
class="form-control"
:class="{'is-invalid':form.errors.has('BadgeType')}"
>
<option value selected>Select BadgeType</option>
<option value="Resident">Resident</option>
<option value="Non-Resident-Expat">Non-Resident Expat</option>
<option value="Non-Resident-LN">Non-Resident LN</option>
<option value="Baron-employee">Baron-employee</option>
</select>
<has-error :form="form" field="BadgeType"></has-error>
</div>
</div>
</form>
</div>
</div>
</div>
Code in script is:
<script>
export default {
// el: "#wrapper2",
data() {
return {
seen: false,
seen2: true,
color: "blue",
size: "20px",
editMode: false,
Companies: {},
employees: {},
form: new Form({
id: "",
BadgeCode: "",
BadgeType: "",
company_id: "",
})
};
},
methods: {
getvalidateion() {
axios.get("api/employee").then(response => {
let data = response.data.data;
if (data) {
data.forEach(element => {
if (this.form.BadgeCode == data.BadgeCode) {
toast.fire({
type: "warning",
title: "The badge code has already been taken."
});
}
});
} else {
console.log("NO DATA");
}
});
},
createemployee() {
this.getvalidateion();
if (this.form.company_id == "") {
toast.fire({
type: "warning",
title: "Please Select the Company."
});
} else if (this.form.BadgeCode == "") {
toast.fire({
type: "warning",
title: "BadgeCode is required."
});
} else if (this.form.BadgeType == "") {
toast.fire({
type: "warning",
title: "Please Select the BadgeType."
});
} else if (this.form.nationality_id == "") {
toast.fire({
type: "warning",
title: "Please Select the Nationality."
});
} else if (this.form.expiredate == "" || this.form.issuedate == "") {
toast.fire({
type: "warning",
title: "Please fill the issuedate or expiredate fileds ."
});
} else if (this.form.photo.length == "") {
toast.fire({
type: "warning",
title: "Please select photo."
});
} else if (
this.form.afghanidatephoto != undefined &&
this.form.afghanidatephoto.length == ""
) {
toast.fire({
type: "warning",
title: "Please select AfghaniDate."
});
} else {
this.form
.post("api/employee")
.then(() => {
// the below function will be use to reload the page
// this.$emit("refreshPage");
$("#addNew").modal("hide");
toast.fire({
type: "success",
title: "employee Created successfully"
});
this.form.reset();
$("#afghanidatephoto").val("");
$("#photo").val("");
Fire.$emit("refreshPage");
})
.catch(e => {
console.log(e);
});
}
},
created() {
Fire.$on("searching", () => {
let query = this.$parent.search;
axios
.get("api/findemployee?q=" + query)
.then(data => {
this.employees = data.data;
})
.catch(() => {});
});
this.loademployees();
this.getvalidateion();
// load the page after 3 secound
Fire.$on("refreshPage", () => {
this.loademployees();
});
}
};
</script>
Code in Modal is:
$table->string('BadgeCode')->unique();
I found the solution instate of data.BadgeCode I should have put element.BadgeCode anyway thanks guys
getvalidateion() {
axios.get(this.url).then(response => {
let data = response.data;
//this.Companies != undefined && this.Companies.length == 0
if (data) {
data.forEach(element => {
this.employees2.push(element.BadgeCode);
if (this.form.BadgeCode == element.BadgeCode) {
toast.fire({
type: "warning",
title: "BadgeCode is already has been taken."
});
}
});
} else {
console.log("NO DATA");
}
});
}
I'm using mean.js to create a system and I change the mongoose part for sequelize and I trying to save multiple Objects from Angular to my database through sequelize.
I followed this answer to create multiple inputs dynamically on the Dia (Day) option for multiple schedules.
And I have my controller like this:
$scope.horarios = [];
$scope.itemsToAdd = [{
Day: '',
StartHour: '',
EndHour: ''
}];
$scope.add = function(itemToAdd) {
var index = $scope.itemsToAdd.indexOf(itemToAdd);
$scope.itemsToAdd.splice(index, 1);
$scope.horarios.push(angular.copy(itemToAdd))
};
$scope.addNew = function() {
$scope.itemsToAdd.push({
Day: '',
StartHour: '',
EndHour: ''
});
console.log($scope.itemsToAdd);
};
and view
<div class="col-xs-12" style="padding: 0" ng-repeat="itemToAdd in itemsToAdd">
<div class="form-group col-xs-12 col-sm-5" >
<label for="Days">Dia</label> <select class="form-control col-xs-12 col-sm-6" data-ng-model="itemToAdd.Day" id="Days" name="Days">
<option value="">---Seleccione uno---</option>
....
</select>
</div>
<div class="form-group col-xs-5 col-sm-3">
<label class="control-label" for="startHour">Hora Inicio</label> <input class="form-control" id="startHour" name="startHour" ng-model="itemToAdd.StartHour" type="time">
</div>
<div class="form-group col-xs-5 col-sm-3">
<label class="control-label" for="endHour">Hora Termino</label> <input class="form-control" id="endHour" name="endHour" ng-model="itemToAdd.EndHour" type="time">
</div>
<div class="col-xs-2 col-sm-1">
<button ng-click="addNew()" class="btn btn-success" style="position: relative; top:26px"><i class="glyphicon glyphicon-plus"></i></button>
</div>
</div>
Then I have my both controllers on client side with Angular:
// Create new course
$scope.create = function( isValid ) {
// Create new course object
var course = new Courses( $scope.course );
course.Schedule = $scope.itemsToAdd;
console.log($scope.course);
// Redirect after save
course.$save( function( response ) {
$scope.closeThisDialog();
notify( 'Genial. El Curso ha sido registrada exitosamente' );
// Clear form fields
$scope.course = '';
$scope.schedule = '';
}, function( errorResponse ) {
$scope.error = errorResponse.data.message;
} );
};
And sequelize:
exports.create = function(req, res) {
var schedule = req.body.Schedule;
req.body.schedule = undefined;
// req.body.userId = req.user.id;
db.Course.create(req.body)
.then(function(course) {
if (!course) {
return res.send('users/signup', {
errors: 'Could not create the course'
});
} else {
schedule.CourseId = course.dataValues.id;
db.Schedule.create(schedule)
.then(function(schedule) {
for (var i = schedule.dataValues.length - 1; i >= 0; i++) {
course.schedule = schedule.dataValues[i];
}
// course.schedule = schedule.dataValues;
})
.catch(function(err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
return res.jsonp(course);
}
})
.catch(function(err) {
return res.status(400)
.send({
message: errorHandler.getErrorMessage(err)
});
});
};
But honestly I don't have a clue how to save it or if my Angular controller is even the correct way to do it. Hope you can help me or give me hint how to do it.
In addition to updating a single instance, you can also create, update, and delete multiple instances at once. The functions you are looking for are called
Model.bulkCreat
http://docs.sequelizejs.com/en/2.0/docs/instances/#working-in-bulk-creating-updating-and-destroying-multiple-rows-at-once