Binding Separate Groups of JSON Data to a UserID Number AngularJS - javascript

I've been having trouble figuring out how to keep data as separate forms, but binding together inside of angularJS. This is for educational and testing purposes so I don't need to worry about setting this data to a db or using any type of storage for now other than the apps session and localstorage. For the test I will hard code into my JS.
I'm uploading a photo to showcase my thoughts and I'll explain it as well:
So my main data is a customers group. I have it set to iterate through and display using ng-repeat. No big worries there. I can add, and update each of these. When I had the proposals attached to the customers json object then when I edited the user, it would delete those proposals and quotes. So I want to keep them separate, but allow them to be called into the DOM by specific user.
My Problem:
Is that I do not know how to bind objects, to objects, and have them update in the dom anytime another action happens. Here is a pen of what I have so far
http://codepen.io/ddavisgraphics/pen/pvRZOv?editors=101.
Example of the Code Data:
var customerArray = [
// Start Customer
//--------------
{
customerID:1,
customer: 'Joe Frankelton',
phone: 1244957323,
email: 'jFrank#gmail.com',
// start address
address: {
line1:'248 Gallows Rd',
city:'Hangtown',
state:'West HangState',
zip:24750
},
}, // End Customer
// Start Customer
//--------------
{
customerID:2,
customer: 'Danny Manny',
phone: 1245423323,
email: 'dman#gmail.com',
// start address
address: {
line1:'253 Cow Run Rd',
city:'Beeftown',
state:'PA',
zip:24750
},
}, // End Customer
];
var proposals = [
{ // Proposal 1
customerID: 1,
projectTitle: 'Gameify Me Captin',
type: 'GameDesign',
deadline: 'Jan. 2, 2015',
deliveryType: 'Files',
problem: 'The problem is that the customer wants to much crap.',
notes: 'clients mother wants to be involved because she designed a peice of toast in 1973',
},
{ // Proposal 2
customerID: 2,
projectTitle: 'Playing',
type: 'Website',
deadline: 'Jan. 2, 2017',
deliveryType: 'Sites',
problem: 'Everything',
notes: 'client will be easy to work with, wants pink and blue',
},
];
var quotes = [
{
customerID: 2,
quoteNum: 2,
projectTitle: 'Project Title',
type: 'Graphic Design',
deadline: 'Jan. 2, 2015',
billableHrs: 11,
hourlyRate: 42.50,
externalCost: 33.99,
tax: 0.6,
}
];

What you can do is to create a viewmodel for customer by mapping the data from multiple sources, i.e customers, proposals and quotes.
You can use customerID to do the linking, example:
customer.proposals = proposals.filter(function(prop){
return prop.customerID === custId;
});
So you would do:
function getMappedCustomer() {
return customerArray.map(function(customer){
var custId = customer.customerID;
customer.proposals = proposals.filter(function(prop){ return prop.customerID === custId;});
customer.quotes = quotes.filter(function(quot){ return quot.customerID === custId; });
return customer;
});
}
// Init current data
$scope.customers = getMappedCustomer();
Similarly do it when you do the maping of updated customer. If you want to preserve customerArray use angular.copy(customerArray) and do the mapping on it.
Demo

Related

Sending data to service array brute force

I can't find an answer to my question, can you help me friends
what kind of requests, I get: facebook, linkedin, reddit
I don't want to write a lot of code, so I want to ask you how I can make
How do I create a check loop, and send the data (the data is the same for all services)
to go through and find the right service. send the right service and data. Again, the data for all services is the same
as you can see, I write a lot of conditional statements, and I don't like it, I want to put
I use ejs, express
I just want to get rid of a lot of code..
everything into one loop and work
var servies = ["facebook", "linkedin", "reddit"]
servies.forEach(service => {
console.log(service);
});
if (service == "linkedin") {
res.render('linkedin', {
id: xssFilters(id),
name: xssFilters(name),
image: xssFilters(photo),
firstName: xssFilters(firstName),
})
}
if (service == "reddit") {
res.render('reddit', {
id: xssFilters(id),
name: xssFilters(name),
image: xssFilters(photo),
firstName: xssFilters(firstName),
})
}
if (service == "facebook") {
res.render('facebook', {
id: xssFilters(id),
name: xssFilters(name),
image: xssFilters(photo),
firstName: xssFilters(firstName),
})
}
You can try
var servies = ["facebook", "linkedin", "reddit"]
servies.forEach(service => {
console.log(service);
res.render(service, {
id: xssFilters(id),
name: xssFilters(name),
image: xssFilters(photo),
firstName: xssFilters(firstName),
})
});
since in your example code, you don't do anything different between the different services, but only replace the string name of the service, and you already have a loop for that.

Refresh data in table after creating a record

In my Ui5 app I have added CREATE operation using oData. But when i am trying to create entry it is getting added in backend but in table it is showing NO DATA (refer image 1). but when I refresh the same page it is there (refer image 2). With single entry ,it is automatically getting refreshed 
problem is with Multiple entries.
Please refer the screenshot and code for clear view.
After Clicking CREATE button:
After Refreshing WebPage:
onCreate: function() {
var oModel = this.getView().getModel();
var contactEntry1 = {
ProductID: 'KT-1960',
TypeCode: 'AD',
SupplierID: '0100000001',
TaxTarifCode: 1,
Category: 'Notebooks',
MeasureUnit: 'EA',
CurrencyCode: 'EUR',
Name: 'Urvish',
Description: 'First batch entry',
},
contactEntry2 = {
ProductID: 'KT-1982',
TypeCode: 'AD',
SupplierID: '0100000001',
TaxTarifCode: 1,
Category: 'Notebooks',
MeasureUnit: 'EA',
CurrencyCode: 'EUR',
Name: 'Urvish',
Description: 'Second batch entry',
};
oModel.setUseBatch(true);
oModel.create('/ProductSet', contactEntry1);
oModel.create('/ProductSet', contactEntry2);
oModel.refresh(true);
},
Looks like that you use the asynchronous operation for create but think that they are synchronous.
In order to fix this out, you can send these 2 create in one $batch request, but use the createEntry method of ODataModel, in order to use the submitChanges method, the callback of which, will be called once two of items are successfully created on the backend side (the below code example should be relevant for v2.ODataModel):
var oTableItemsBinding = oTable.getBinding("items");
// define the group ID, which will be used later on
var aCurrentDeferredGroups = oModel.getDeferredGroups();
oModel.setDeferredGroups(aCurrentDeferredGroups.concat("createProductGroup"));
// create two entries one by one, specifying the 'groupId' parameter
oModel.createEntry("/ProductSet", {
properties: contactEntry1,
groupId: "createProductGroup"
});
oModel.createEntry("/ProductSet", {
properties: contactEntry2,
groupId: "createProductGroup"
});
// send 2 requests in one $batch, passing the name of the 'groupId'
oModel.submitChanges({
groupId: "createProductGroup",
success: function() {
// no need to call refresh() as the model already does it by default (See "refreshAfterChange")
}.bind(this)
});
If your service does not support $batch requests, then you can still use the create method, but make use of it's success callback to be sure that the entry has been persisted in the backend.

Mongoose updating a document by removing a single object from document

Can't find a solution for it :(
I'm doing a contacts app using Node, express and mongoose.
when a user goes to the route /contact/:id
this query gets executed:
Contact.findOne(req.dbQuery, function(err, data) {
res.json(data);
});
The Response is:
{
_id: 57 d71ceb57658ba24866a1b0,
__v: 0,
firstName: ['Doe', 'text'],
lastName: ['John', 'text'],
id: 4,
homePhone: ['', 'tel'],
cellPhone: ['', 'tel'],
birthday: ['', 'date'],
website: ['', 'url'],
address: ['test Adress', 'text'],
}
Each item in the array is getting displayed on the page as a label and a textbox
using ng-repeat.
Next to each textbox I have an X button to remove a textbox.
On each X button there's ng-click="remove(field)"
$scope.remove = function(field){ //field can be 'homePhone' or any item
delete $scope.record[field];
$scope.record.$update(function(updatedRecord){
$scope.record = updatedRecord;
})
};
Problem is, When I'm clicking on the X button and calling
remove('homePhone') (or any of the fields - 'cellPhone' or any other)
i'm sending the correct data to the server via req.body (I can see the data
without the removed field) but getting a response including the field I just
removed.
On the server I'm executing:
Contact.findOneAndUpdate({
_id: contact._id
}, req.body, {
upsert: true,
new: true
}, function(err, data) {
res.json(data);
});
I also have an "add new field" button that is adding a textbox by adding an item
to the array. I'm executing the same query on add new field
This is why I use {upsert: true, new: true}
Will I have to change everything?
Thanks a lot
please use $unset operator to remove any field from the document. that is the preferred way or removing fields from document when performing an update.

Associate multiple resources to service appointment entity using OData endpoint with javascript in CRM 2013

My goal is to create a service appointment record associated with multiple resources.
For this purpose I have followed this MSDN example.
The problem rises when I try to associate multiple resources for one particular service appointment, CRM server will store only the last one(1 record). Following demonstrates my code:
//attendees =[... array of resource ids]
var serviceAppointment = {
ScheduledStart: new Date("12/22/2014 4:53 PM"),
ScheduledEnd: new Date("12/22/2014 5:53 PM"),
Subject: "test service",
ServiceId:
{
//// hardcoded id for simplicity
Id: "6f795012-ca55-e411-aa38-00155d0a0948",
LogicalName: "service"
}
};
SDK.JQuery.createRecord(serviceAppointment,"ServiceAppointment"
,function(sa){
for(var i=0;i<attendees.length;i++)
{
var activityParty = {
PartyId:
{
Id: attendees[i],
LogicalName: "systemuser",
},
ActivityId:
{
Id: sa.ActivityId,
LogicalName: "serviceappointment",
},
ParticipationTypeMask:
{
//See http://msdn.microsoft.com/en-us/library/gg328549.aspx
//10 is for resource
Value: 10
}
};
SDK.JQuery.createRecord(activityParty,"ActivityParty", function(ap){debugger;},errorHandler);
}
}
,errorHandler);
As far as I debugged the code the create record is being executed properly without no exception. I believe I'm missing a configuration flag somewhere in my code and CRM is considering one to one association rather than one to many.
Any clues?
I could solve this issue by passing array of parties in service appointment record at the first place rather than inserting them one-by-one at the end. Here is the code which works:
var parties =[];
for(var i=0;i< e.event.attendees.length;i++)
{
var activityParty = {
PartyId:
{
Id: e.event.attendees[i],
LogicalName: "systemuser",
},
ParticipationTypeMask:
{
//See http://msdn.microsoft.com/en-us/library/gg328549.aspx
//10 is for resource
Value: 10
}
}
parties.push(activityParty);
}
var serviceAppointment = {
ScheduledStart: e.event.start,
ScheduledEnd: e.event.end,
Subject: e.event.title,
ServiceId:
{
Id: "6f795012-ca55-e411-aa38-00155d0a0948",
LogicalName: "service"
},
serviceappointment_activity_parties: parties,
};
SDK.JQuery.createRecord(serviceAppointment,"ServiceAppointment"
,function(sa){
debugger;
e.event.ActivityId = serviceAppointmentActivityId = sa.ActivityId;
}
,errorHandler);
}
hope it helps somebody out there.

Make ember to resolve hasMany relationship when loading

I'm currently facing a big problems for days. I'm using ember simple-auth plugin which provide me a session object accessible through the code or the templates. That session object store the account information such as username, id and rights.
My models are like this :
App.Right = DS.Model.extend({
label: DS.attr('string', { defaultValue: undefined })
});
App.Right.FIXTURES = [
{
id: 1,
label: 'Admin'
}, {
id: 2,
label: 'Manager'
}, {
id: 3,
label: 'User'
}
];
App.User = DS.Model.extend({
username: DS.attr('string'),
rights: DS.hasMany('right', {async: true})
});
App.User.FIXTURES = [
{
id: 1,
username: "Someone",
rights: [1]
}
];
Then I have (as specified on the simple-auth documentation) this setup :
App.initializer({
name: 'authentication',
initialize: function(container, application) {
Ember.SimpleAuth.Session.reopen({
account: function() {
var userId = this.get('userId');
if (!Ember.isEmpty(userId)) {
return container.lookup('store:main').find('user', userId);
}
}.property('userId')
});
...
}
});
Inside one of my view I'm doing this:
this.get('context.session.account.rights').toArray()
but it gives me an empty array. That piece of code is executed inside an Ember.computed property.
The question is how can I resolve the childrens of account before rendering the view ?
Since async: true this.get('context.session.account.rights') will return a promise object so you will have to use this.get('context.session.account.rights').then(... see: http://emberjs.com/api/classes/Ember.RSVP.Promise.html#method_then
Okay so I finally got it to work. It doesn't solve the original question because the original question was completely stupid. It's just IMPOSSIBLE to resolve relationships synchronously when you use the async: true. Trying to resolve it in advance is NOT the solution because you will still not know when it has actually resolved.
So here is the solution:
$.each(this.get('cellContent.buttonList'), function(i, button) {
button.set('hasAccess', false);
this.get('context.session.account').then(function(res) {
res.get('rights').then(function(result) {
button.set('hasAccess', Utils.hasAccess(result.toArray(), button.rights));
});
});
});
Using the following cellContent.buttonList definition:
buttonList: [
Ember.Object.create({
route: 'order',
label: 'Consult',
rights: 'all'
}), Ember.Object.create({
route: 'order.edit',
label: 'Edit',
rights: [1, 2]
})
]
Explanation
We have to use Ember.Object in order to have access to the set method. Using an Ember object is very handy. It allows us to change the value of properties after the render process making the view to update according to the new value you just set.
Because it updates the view, you don't have to care anymore whether your model has resolved or not.
I hope this will help people as much as it helps me.

Categories

Resources