Simplify angular controller posting to Firebase using AngularFire - javascript

I'm new to angular but picking it up quickly. I have this controller that works, based on demo code ive hacked together, but there has to be an easier cleaner way to get all the fields and post so if i want to add a new field i dont need to keep adding it in the various locations.
Heres the controller:
'use strict';
angular.module('goskirmishApp').controller('addEvent', function ($scope, fbutil, $timeout) {
// synchronize a read-only, synchronized array of messages, limit to most recent 10
$scope.messages = fbutil.syncArray('messages', {limit: 10});
// display any errors
$scope.messages.$loaded().catch(alert);
// provide a method for adding a message
$scope.addMessage = function(newEventName,newEventType,newStartDate,newStartTime,newEndDate,newEndTime,newEventDescription,newAddress,newPostcode,newTicketInformation,newBookLink) {
if( newEventName ) {
// push a message to the end of the array
$scope.messages.$add({
eventName: newEventName,
eventType: newEventType,
startDate: newStartDate,
startTime: newStartTime,
endDate: newEndDate,
endTime: newEndTime,
eventDescription: newEventDescription,
address: newAddress,
postcode: newPostcode,
ticketInformation: newTicketInformation,
bookLink: newBookLink
})
// display any errors
.catch(alert);
}
};
function alert(msg) {
$scope.err = msg;
$timeout(function() {
$scope.err = null;
}, 5000);
}
});
And the view:
<h2>Add Event</h2>
<p class="alert alert-danger" ng-show="err">{{err}}</p>
<form role="form">
<div class="form-group">
<label>Event Name</label>
<input class="form-control" type="text" ng-model="newEventName">
</div>
<div class="form-group">
<label>Event Type</label>
<select class="form-control" ng-model="newEventType">
<option value="" disabled selected>Game type</option>
<option value="milsim">Skirmish</option>
<option value="milsim">Special Event</option>
<option value="milsim">Weekender</option>
<option value="milsim">Milsim</option>
</select>
</div>
<div class="form-group">
<label>Start Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="newStartDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="newStartTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>End Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="newEndDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="newEndTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>Event Description</label>
<textarea class="form-control" rows="4" ng-model="newEventDescription"></textarea>
</div>
<div class="form-group">
<label>Address</label>
<input class="form-control" ng-model="newAddress">
</div>
<div class="form-group">
<label>Postcode</label>
<input class="form-control" ng-model="newPostcode">
</div>
<div class="form-group">
<label>Ticket Information</label>
<textarea class="form-control" rows="4" ng-model="newTicketInformation"></textarea>
</div>
<div class="form-group">
<label>Booking Link</label>
<input class="form-control" ng-model="newBookLink">
</div>
<button type="submit" class="btn btn-danger" ng-click="addMessage(newEventName,newEventType,newStartDate,newStartTime,newEndDate,newEndTime,newEventDescription,newAddress,newPostcode,newTicketInformation,newBookLink,newLat,newLong,newApproved);newEventName = null;newEventType = null;newStartDate = null;newStartTime = null;newEndDate = null;newEndTime = null;newEventDescription = null;newAddress = null;newPostcode = null;newTicketInformation = null;newBookLink = null;">Add Event</button>
</form>
Help is greatly appreciated!

Define all your input in a object that you will be directly send send to firebase
For example init in your controller this :
$scope.form = {};
After in your template just define your input as 'form attributes'.
<h2>Add Event</h2>
<p class="alert alert-danger" ng-show="err">{{err}}</p>
<form role="form">
<div class="form-group">
<label>Event Name</label>
<input class="form-control" type="text" ng-model="form.eventName">
</div>
<div class="form-group">
<label>Event Type</label>
<select class="form-control" ng-model="form.eventType">
<option value="" disabled selected>Game type</option>
<option value="milsim">Skirmish</option>
<option value="milsim">Special Event</option>
<option value="milsim">Weekender</option>
<option value="milsim">Milsim</option>
</select>
</div>
<div class="form-group">
<label>Start Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="form.startDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="form.startTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>End Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="form.endDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="form.endTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>Event Description</label>
<textarea class="form-control" rows="4" ng-model="form.eventDescription"></textarea>
</div>
<div class="form-group">
<label>Address</label>
<input class="form-control" ng-model="form.address">
</div>
<div class="form-group">
<label>Postcode</label>
<input class="form-control" ng-model="form.postcode">
</div>
<div class="form-group">
<label>Ticket Information</label>
<textarea class="form-control" rows="4" ng-model="form.ticketInformation"></textarea>
</div>
<div class="form-group">
<label>Booking Link</label>
<input class="form-control" ng-model="form.bookLink">
</div>
<button type="submit" class="btn btn-danger" ng-click="addMessage()">Add Event</button>
</form>
and directly in your addMessage function
$scope.addMessage = function() {
if( $scope.form.eventName ) {
// push a message to the end of the array
$scope.messages.$add($scope.form)
// display any errors
.catch(alert);
//Reset your form
$scope.form = {};
}
};

Related

Firebase Realtime database update

Hello guys my firebase real-time database update function is updating all the data with new data, I'm attaching the image of the database before the update
And after the update all the fields of A and B are changed into C, the source code is available below :
Frontend:
<form onsubmit="return false">
<input type="hidden" id="hiddenId">
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Course Code</label>
<input type="text" class="form-control uname-box" id="popupCourseCode" aria-describedby="emailHelp" placeholder="Course Code">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Course Title</label>
<input type="text" class="form-control uname-box" id="popupCourseTitle" aria-describedby="emailHelp" placeholder="Course Title">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Subject</label>
<input type="text" class="form-control uname-box" id="popupSubject" aria-describedby="emailHelp" placeholder="Subject">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Credits</label>
<input type="number" class="form-control uname-box" id="popupCredits" aria-describedby="emailHelp" placeholder="Credits">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Grades</label>
<input type="text" class="form-control uname-box" id="popupGrades" aria-describedby="emailHelp" placeholder="Grades">
</div>
</div>
</form>
Function:
function update() {
firebase.database().ref('academics').orderByKey().once('value', snap => {
snap.forEach((data) => {
var popupCourseCode = document.getElementById('popupCourseCode');
var popupCourseTitle = document.getElementById('popupCourseTitle');
var popupSubject = document.getElementById('popupSubject');
var popupCredits = document.getElementById('popupCredits');
var popupGrades = document.getElementById('popupGrades');
var updates = {
courseCode: popupCourseCode.value,
courseTitle: popupCourseTitle.value,
subject: popupSubject.value,
credits: popupCredits.value,
grade: popupGrades.value,
}
firebase.database().ref('academics/' + data.key).update(updates)
// alert('updated')
console.log(`Update FunctionKey!!!!!!!!!!!! >>>>>>>>> ${data.key}`)
})
// console.log(`Remove FunctionKey!!!!!!!!!!!! >>>>>>>>> ${data.key}`)
})
}
Please provide me a solution. Thanks in anticipation

form inputs data failed to be received when element is inserted with JavaScript

I am trying to dynamically change the html of parent form element to display according the what the user wants to upload, then retrieve the data from that child element. I saved the list of children to dynamically input in the js folder leaving the parent form element empty.
The issue is:
a) When I dynamically input the preferred child element according to what user wants to upload, It doesn't retrieve the values even though it shows in the DOM that the element is there.
b) Whereas if I statically input the child element in html folder, it works just fine. but when the child is changed again, its still the statically inputted values I get back.
please how do I go about this?? Here's the codepen showing it.
<div class="upload-box container mt-3">
<div class="title-box-d">
<h3 class="title-d upload-type">Uploading A Car</h3>
</div>
<div class="box-collapse-wrap form ">
<div class="form-group mb-5">
<div class="row">
<div class="col-md-4">
<label for="upload">What Do You Want To Upload?</label>
<select class="form-control form-control-lg form-control-a" id="upload">
<option value="cars">Car</option>
<option value="houses">House/Home</option>
<option value="land">Land Properties</option>
</select>
</div>
</div>
</div>
<form class="form-a form-upload">
</div>
</form>
</div>
</div>
The JS
///////////////////////
/*--/ Project Logic /--*/
//////////////////////
const projectData = {
uploadCategories: {
carForm: ` <div class="row">
<div class="col-md-8 mb-2">
<div class="form-group">
<label for="file">Add Photo</label>
<input type="file" id="file" accept="image/*" multiple="multiple"
class="form-control form-control-lg form-control-a">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control form-control-lg form-control-a" id="location">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="brand">Car Brand</label>
<input type="text" class="form-control form-control-lg form-control-a" id="brand"
placeholder="Eg Toyota, Lexus etc">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="car-model">Car Model</label>
<input type="text" class="form-control form-control-lg form-control-a" id="car-model"
placeholder="eg Venza, Sienna, Corolla Etc">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="year">Year</label>
<input type="number" class="form-control form-control-lg form-control-a" id="year">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="condition">Condition</label>
<select class="form-control form-control-lg form-control-a" id="condition">
<option>Brand New</option>
<option>Nigerian Used</option>
<option>Foreign Used</option>
</select>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="transmission">Transmission</label>
<select class="form-control form-control-lg form-control-a" id="transmission">
<option>Automatic</option>
<option>Manual</option>
</select>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="registered">Registered?</label>
<select class="form-control form-control-lg form-control-a" id="registered">
<option>Yes</option>
<option>No</option>
</select>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="mileage">Mileage</label>
<input type="number" class="form-control form-control-lg form-control-a" id="mileage"
placeholder="Mileage (km)">
<div class="form-group mt-3">
<label for="price">Price</label>
<input type="number" class="form-control form-control-lg form-control-a" id="price">
</div>
</div>
</div>
<div class="col-md-8 mb-2">
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control form-control-lg form-control-a"
placeholder="Add more description to your Ad" id="description" cols="30" rows="30"
style="height: 10rem;"></textarea>
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-b">Upload</button>
</div>
</div>`,
houseForm: `<div class="row">
<div class="col-md-8 mb-2">
<div class="form-group">
<label for="file">Add Photo</label>
<input type="file" id="file" accept="image/*" multiple="multiple"
class="form-control form-control-lg form-control-a">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control form-control-lg form-control-a" id="location">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control form-control-lg form-control-a" id="title"
placeholder="Title or name of the Property">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="area">Property Size (sqm)</label>
<input type="number" class="form-control form-control-lg form-control-a" id="area">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="bedrooms">Bedrooms</label>
<input type="number" class="form-control form-control-lg form-control-a" id="bedrooms">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="bathrooms">Bathrooms</label>
<input type="number" class="form-control form-control-lg form-control-a" id="bathrooms">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="sale-status">For Sale Or rent?</label>
<select class="form-control form-control-lg form-control-a" id="sale-status">
<option>For Sale</option>
<option>For Rent</option>
</select>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="garage">Garage</label>
<input type="number" class="form-control form-control-lg form-control-a" id="garage">
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="price">Price</label>
<input type="number" class="form-control form-control-lg form-control-a" id="price">
</div>
</div>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="amenities">Other Amenities</label>
<select class="form-control form-control-lg form-control-a" id="amenities" multiple style="height: 10rem;">
<option>Parking Space</option>
<option>24 Hours Electricity</option>
<option>Internet</option>
<option>Air Conditioning</option>
<option>Security</option>
<option>Balcony</option>
<option>Tile Floor</option>
<option>Dish Washer</option>
<option>Dining Area</option>
<option>Kitchen Cabinet</option>
<option>Kitchen Shelf</option>
<option>Wardrobe</option>
<option>WIFI</option>
<option>POP Ceiling</option>
<option>Prepaid Meter</option>
<option>Concrete Flooring</option>
</select>
</div>
</div>
<div class="col-md-8 mb-2">
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control form-control-lg form-control-a" placeholder="Add more description to your Ad"
id="description" cols="30" rows="30" style="height: 10rem;"></textarea>
</div>
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-b">Upload</button>
</div>`,
landForm: `<div class="row">
<div class="col-md-8 mb-2">
<div class="form-group">
<label for="file">Add Photo</label>
<input type="file" id="file" accept="image/*" multiple="multiple"
class="form-control form-control-lg form-control-a">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control form-control-lg form-control-a" id="location">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control form-control-lg form-control-a" id="title"
placeholder="Title or name of the Land.">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="area">Property Size (sqm)</label>
<input type="number" class="form-control form-control-lg form-control-a" id="area">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="land-type">Type Of Land</label>
<select class="form-control form-control-lg form-control-a" id="land-type" placeholder="What Type of Land is This?">
<option>Commercial Land</option>
<option>Farmland</option>
<option>Industrial Land</option>
<option>Mixed-use LAnd</option>
<option>Quarry</option>
<option>Residential Land</option>
</select>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="row">
<div class="col-12">
<div class="form-group">
<label for="sale-status">For Sale Or Lease?</label>
<select class="form-control form-control-lg form-control-a" id="sale-status">
<option>For Sale</option>
<option>For Lease</option>
</select>
</div>
</div>
<div class="col-12">
<div class="form-group">
<label for="price">Price</label>
<input type="number" class="form-control form-control-lg form-control-a" id="price">
</div>
</div>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="amenities">Other Amenities</label>
<select class="form-control form-control-lg form-control-a" id="amenities" multiple style="height: 10rem;">
<option>Parking Space</option>
<option>Electric Supply</option>
<option>Domestic Sewage</option>
<option>Gas Supply</option>
<option>Rain Water Drainage</option>
<option>Water Supply</option>
</select>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control form-control-lg form-control-a" placeholder="Add more description to your Ad"
id="description" cols="30" rows="30" style="height: 10rem;"></textarea>
</div>
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-b">Upload</button>
</div>`
},
fromInputs: {
Name: $('#title'),
Brand: $('#brand'),
Model: $('#car-model'),
Location: $('#location'),
Description: $('#description'),
Status: $('#sale-status'),
Price: $('#price'),
Bedrooms: $('#bedrooms'),
Bathrooms: $('#bathrooms'),
Garage: $('#garage'),
Area: $('#area'),
Amenities: $('#amenities'),
'Type Of Land': $('#land-type'),
Year: $('#year'),
Condition: $('#condition'),
Transmission: $('#transmission'),
Registered: $('#registered'),
Mileage: $('#mileage'),
},
formImages: {
dataReferenceId: 'dataid',
images: []
},
dataToSubmit : ''
};
/*--/ Admin Page Code /--*/
// Check what typemof data user wants to upload and display from related to that
$('#upload').change(e => {
switch (e.target.value) {
case 'houses':
$('.upload-type').text('Uploading A House');
$('.form-upload').html(projectData.uploadCategories.houseForm);
break;
case 'land':
$('.upload-type').text('Uploading A Land');
$('.form-upload').html(projectData.uploadCategories.landForm);
break;
default:
$('.upload-type').text('Uploading A Car');
$('.form-upload').html(projectData.uploadCategories.carForm);
break;
}
});
// GET ALL UPLOAD FORM DATA INPUTED
$('.form-upload').submit(function (event) {
event.preventDefault();
// Check what category user wants to upload
const uploadCategory = $('#upload').val();
// GET ALL THE DATA FOR A FORM SESSION UPLOADED
const data = Object.entries(projectData.fromInputs).map(([key, value]) => [key, value && value.val()]);
// FILTER THE DATA TO RETURN ON THOSE WITH VALUES
const filteredData = Object.fromEntries(
data.filter(([key, value]) => value
));
console.log(filteredData);
// projectData.dataToSubmit = filteredData;
});
CODEPEN: https://codepen.io/genral-walker/pen/vYgqbvL
Main problem is that you're caching reference to elements that might not be in DOM at the time. You should store a selector instead:
fromInputs: {
Name: '#title',
Brand: '#brand',
Model: '#car-model',
Location: '#location',
Description: '#description',
Status: '#sale-status',
Price: '#price',
Bedrooms: '#bedrooms',
Bathrooms: '#bathrooms',
Garage: '#garage',
Area: '#area',
Amenities: '#amenities',
'Type Of Land': '#land-type',
Year: '#year',
Condition: '#condition',
Transmission: '#transmission',
Registered: '#registered',
Mileage: '#mileage',
},
And then look it up later:
const data = Object.entries(projectData.fromInputs).map(([key, value]) => {
console.log(key, value);
const $el = $(value);
return [key, $el.length && $el.val()];
});
https://codepen.io/genral-walker/pen/vYgqbvL?editors=1111

Auto propagate form consisting of different input types from json data dynamically

I want to auto populate a form consisting of different input types (select boxes and text areas) dynamically. I am able to get input boxes working just fine, here is an example:
function autofill(){
var data = [{visible_retail: "0", brand: "cool!", description: "hello there!"}];
console.log(data);
data.map(function(item) {
for (var key in item)
$('input[id=product-'+key+']').val(item[key]);
}).join();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="product-form">
<div class="form-group row">
<label for="product-visible_retail" class="col-4 col-form-label">Visibility (Retail)</label>
<div class="col-8">
<select class="form-control" id="product-visible_retail" required>
<option value="1">Shown</option>
<option value="0">Hidden</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="product-brand" class="col-4 col-form-label">Brand</label>
<div class="col-8">
<input class="form-control" type="text" value="" id="product-brand" maxlength="50" required>
</div>
</div>
<div class="form-group row">
<label for="product-description" class="col-4 col-form-label">Description</label>
<div class="col-8">
<textarea class="form-control" id="product-description" rows="4" cols="50" maxlength="65535" required></textarea>
</div>
</div>
</form>
<button onclick="autofill()">auto fill</button>
Edit: the form I posted is just an example. In reality I have hundreds of fields that need to be auto propagated. Hence defining them individually really isn't an optimal.
The issue is that a textarea control is NOT an input. And also, you should use .html() or .text() to set a value in it.
I did a little modification to your code:
function autofill(){
var data = [{visible_retail: "0", brand: "cool!", description: "hello there!"}];
console.log(data);
data.map(function(item) {
for (var key in item)
if(key == "description")
$('#product-' + key).text(item[key]);
else if(key == "visible_retail")
$('#product-' + key).val(item[key]);
else
$('input[id=product-'+key+']').val(item[key]);
}).join();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="product-form">
<div class="form-group row">
<label for="product-visible_retail" class="col-4 col-form-label">Visibility (Retail)</label>
<div class="col-8">
<select class="form-control" id="product-visible_retail" required>
<option value="1">Shown</option>
<option value="0">Hidden</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="product-brand" class="col-4 col-form-label">Brand</label>
<div class="col-8">
<input class="form-control" type="text" value="" id="product-brand" maxlength="50" required>
</div>
</div>
<div class="form-group row">
<label for="product-description" class="col-4 col-form-label">Description</label>
<div class="col-8">
<textarea class="form-control" id="product-description" rows="4" cols="50" maxlength="65535" required></textarea>
</div>
</div>
</form>
<button onclick="autofill()">auto fill</button>
You can do something like this with JQuery to add rows/columns dynamically. I saw your question in the comments. CSS class of your table row should be something like this. <tr class="item-row"></tr>
$("#addrow").click(function(){
$(".item-row:last").after('<tr class="item-row"><td class="item-name"><div class="delete-wpr"><textarea class="item_name">Item Name</textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div></td><td class="description"><textarea class="description_val">Description</textarea></td><td><textarea class="cost">N0</textarea></td><td><textarea class="qty">0</textarea></td><td><span class="price">N0</span></td></tr>');
if ($(".delete").length > 0) $(".delete").show();
bind();
});
bind();
$(".delete").live('click',function(){
$(this).parents('.item-row').remove();
if ($(".delete").length < 2) $(".delete").hide();
});
we were way off. Here is the super simple solution...
function autofill(){
var data = [{visible_retail: "0", brand: "cool!", description: "hello there!"}];
console.log(data);
data.map(function(item) {
for (var key in item)
$('#product-'+key).val(item[key]);
}).join();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="product-form">
<div class="form-group row">
<label for="product-visible_retail" class="col-4 col-form-label">Visibility (Retail)</label>
<div class="col-8">
<select class="form-control" id="product-visible_retail" required>
<option value="1">Shown</option>
<option value="0">Hidden</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="product-brand" class="col-4 col-form-label">Brand</label>
<div class="col-8">
<input class="form-control" type="text" value="" id="product-brand" maxlength="50" required>
</div>
</div>
<div class="form-group row">
<label for="product-description" class="col-4 col-form-label">Description</label>
<div class="col-8">
<textarea class="form-control" id="product-description" rows="4" cols="50" maxlength="65535" required></textarea>
</div>
</div>
</form>
<button onclick="autofill()">auto fill</button>

integrating dropzone with normal form

I have successfully integrated dropzone with my form using jquery. However, I have an issue with validation of the other form inputs. It seems the other form inputs do not respect the validation such as "required". I also tried using parsley for validation but does not work. when I remove the dropzone field, the validation works well.
Here is the form.
<form class="form-vertical"
id="createPropertyForm"
enctype="multipart/form-data"
method="POST"
>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Country</label>
<div class="inputGroupContainer">
<input id="country"
name="country" placeholder="Country" class="form-control" required
value="" type="text">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">County</label>
<div
class="inputGroupContainer">
<input id="county"
name="county" placeholder="County" class="form-control" required value=""
type="text">
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Town</label>
<div class=" inputGroupContainer">
<input id="town" name="town"
placeholder="Town" class="form-control" required value="" type="text">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">Postcode</label>
<div class="inputGroupContainer">
<input id="postcode"
name="postcode" placeholder="Postcode" class="form-control" required
value=""
type="text">
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Description</label>
<div class=" inputGroupContainer">
<textarea id="description"
name="description" placeholder="Description" class="form-control"
required="true" value="" type="text"></textarea>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">Address</label>
<div class="inputGroupContainer">
<input id="address" name="address"
placeholder="Address" class="form-control" required value="" type="text">
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Bedrooms</label>
<div class=" inputGroupContainer">
<select class=" form-control"
name="bedrooms" id="bedrooms" required>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label
">Bathrooms</label>
<div class=" inputGroupContainer">
<select
class="selectpicker bathrooms form-control" name="bathrooms"
id="bathrooms"
required>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Price</label>
<div class="inputGroupContainer">
<input id="price" name="price"
placeholder="Price" class="form-control" required value="" type="number">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">Property Type</label>
<div class=" inputGroupContainer">
<select
class="selectpicker form-control" name="propertyType" id="propertyType">
<option
value="">Choose type</option>
<?php
foreach
($propertyTypes as $propertyType) {
?>
<option value="<?=
$propertyType->id ?>"><?= $propertyType->title ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Type</label>
<div class="col-md-12">
<div class="col-md-6 ">
<label><input type="radio"
name="type" class="form-control type" required>Sale</label>
</div>
<div class="col-md-6">
<label><input type="radio"
name="type" class="form-control type" required>Rent</label>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">Upload Image</label>
<div class=" inputGroupContainer">
<div class="dropzone"
id="create-dropzone" >
<div class="fallback">
<input name="file"
type="file" required/>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="dropzone-previews"></div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<button class="btn btn-success btn-lg"
type="submit" id="submitCreateForm"> Submit </button>
</div>
</form>.
Here is the jquery code:
// Parsley for form validation
$('#createPropertyForm').parsley();
$('#editPropertyForm').parsley();
Dropzone.options.createDropzone = {
url: `${baseUrl}administrator/properties`,
autoProcessQueue: false,
parallelUploads: 1,
maxFiles: 1,
maxFileSize:2048,
uploadMultiple: false,
acceptedFiles: "image/*",
init: function () {
var submitButton = document.querySelector("#submitCreateForm");
var wrapperThis = this;
submitButton.addEventListener("click", function (e) {
e.preventDefault();
if (wrapperThis.files.length) {
wrapperThis.processQueue();
} else {
wrapperThis.submit();
}
});
this.on("addedfile", function (file) {
var removeButton = Dropzone.createElement("<button class='btn btn-block btn-danger'><i class='fa-times fa'></button>");
removeButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
wrapperThis.removeFile(file);
});
file.previewElement.appendChild(removeButton);
});
this.on('sending', function (data, xhr, formData) {
formData.append("country", $("#country").val());
formData.append("county", $("#county").val());
formData.append("town", $("#town").val());
formData.append("postcode", $("#postcode").val());
formData.append("description", $("#description").val());
formData.append("address", $("#address").val());
formData.append("bathrooms", $("#bathrooms").val());
formData.append("price", $("#price").val());
formData.append("bedrooms", $("#bedrooms").val());
formData.append("propertyTypeId", $("#propertyType").val());
formData.append("type", $(".type").val());
});
this.on('success', function (files, response) {
toastr.success(response.message);
setTimeout(function () {
location.reload();
}, 1000);
});
this.on('error', function (file, error, xhr) {
file.status = 'queued';
if (xhr.status === 422){
toastr.error('An error occurred, please confirm that you have filled all inputs and try again');
}else{
toastr.error('An error occurred');
}
});
this.on("maxfilesexceeded", function(file) {
wrapperThis.removeFile(file);
});
}
};

check the angular form is valid in the controller

I am new to angularjs. I have searched for this problem but I found some solutions but none of them were working for me. So, I have a form which is
HTML
<div class=" row col-xs-12 col-md-12">
<div id="candidateInfoCorners" ng-show="showcandidateInfo">
<div class="col-xs-12 col-md-12 info-header">
<h>Candidate Information</h>
</div>
<form class="form-horizontal" role="form" name="Candidateform">
<div class="row">
<div class="col-md-6">
<label class="control-label col-sm-4 candidateNpInDaysLabelPosition" for="noticePeriod">Notice Period In Days :</label>
<div class="col-sm-4">
<input type="number" min="0" ng-model="candidate.noticePeriod" class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateNpInDaysInputPosition"
id="noticePeriod" placeholder="Noticeperiod" autocomplete="off" required="">
</div>
</div>
<div class="col-md-6">
<label class="control-label col-sm-4 candidateCTCLabelPosition" for="ctc">CCTC In Lakhs :</label>
<div class="col-sm-4">
<input type="number" min="0" decimal-places="" ng-model="candidate.ctc" class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition"
id="ctc" placeholder="CCTC" autocomplete="off" required="">
</div>
</div>
<div class="col-md-6">
<label class="control-label col-sm-4 candidateECTCLabelPosition" for="ectc">ECTC In Lakhs :</label>
<div class="col-sm-4">
<input type="number" min="0" decimal-places="" ng-model="candidate.ectc" class="form-control ng-pristine ng-valid-min ng-invalid ng-invalid-required ng-touched candidateECTCInputPosition"
id="ectc" placeholder="ECTC" autocomplete="off" required="">
</div>
</div>
<div class="col-md-6">
<label class="col-sm-4 control-label candidateCommunicatioLabelPosition" for="communication">Communication :</label>
<div class="col-sm-4">
<select class="selectpicker form-control ng-pristine ng-untouched ng-invalid ng-invalid-required candidateCommunicatioSelectPosition"
ng-model="candidate.communication" name="communication" id="communication" required="">
<option value="" selected="">Communication</option>
<option value="Good">Good</option>
<option value="Average">Average</option>
<option value="Poor">Poor</option>
</select>
</div>
</div>
</div>
</form>
</div>
</div>
Now, I have a controller where I am using this form like -
$scope.candidate = {
noticePeriod: '',
ctc: '',
ectc: '',
communication: ''
};
And using it like - $scope.candidate.noticePeriod while getting the value.
Now I don't have any submit for the form, this is going to happen on some another action .
$scope.updateDocument = function() {
//Here I want to check the Form is valid or not
//I tried
//$scope.candidateform.$valid but I am getting an error like
Cannot read property '$valid' of undefined
}
Both functions are in the same controller
Can any one help me with this?
You need to use ng-form
This is how I do it.
I make a parent property like
$scope.myforms = {
Candidateform: {}
};
//HTML will be
<ng-form name="myForms.CandidateForm">...</ng-form>
//TO VALIDATE I DO IT LIKE THIS
$scope.myForms.CandidateForm.$submitted = true // This will run the validators as well, this means form has been submitted.
//OR TO SUBMIT IT PROGRAMATICALLY
$scope.myForms.CandidateForm.$valid
You have some errors in your code, You name your form "Candidateform" and then in controller you are only using $scope.candidate. Change that to $scope.CandidateForm
function Controller($scope) {
$scope.master = {};
$scope.user = {
name: "",
email: ""
};
$scope.update = function(user) {
//$scope.master = angular.copy(user);
console.log($scope.master)
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html ng-app>
<div ng-app="demo1">
<div ng-controller="Controller">
<ng-form novalidate class="simple-form" name="master">
<legend>User Profile</legend>
<div class="control-group-error">
<label class="control-label" for="input-error">Name</label>
<div class="controls">
<input type="text" name="username" ng-model="user.name">
<span class="help-inline">Please correct the error</span>
</div>
<label>E-mail</label>
<input type="email" name="email" ng-model="user.email">
</div>
</ng-form>
<button class="btn btn-primary" ng-click="update(user)">Save</button>
<br />
<pre>{{master.$valid}}</pre>
</div>
</div>
</html>

Categories

Resources