We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to add 'createdBy' field in appointments?

Thread ID:

Created:

Updated:

Platform:

Replies:

149221 Nov 19,2019 11:10 AM UTC Nov 25,2019 09:30 AM UTC Angular - EJ 2 7
loading
Tags: Schedule
Youssef Lakdime
Asked On November 19, 2019 11:10 AM UTC


I am implementing the Syncfusion Scheduler into my MEAN-app. (I am using this code https://www.syncfusion.com/forums/143958/data-binding-issue )
Everything works well, however i want to add a custom field, 'createdBy' that assigns the logged in users' email address, so I can only show the appointments of that user, and not all the appointments in the database. Below is the code to add appointments.

app.post("/BatchData", (req, res) => {
console.log(req.body);
var eventData = [];
if (req.body.action == "insert" || (req.body.action == "batch" && req.body.added.length > 0)) {
(req.body.action == "insert") ? eventData.push(req.body.value) : eventData = req.body.added;
for (var i = 0; i < eventData.length; i++) {
var sdate = new Date(eventData[i].StartTime);
var edate = new Date(eventData[i].EndTime);
eventData[i].StartTime = (new Date(+sdate - (sdate.getTimezoneOffset() * 60000)));
eventData[i].EndTime = (new Date(+edate - (edate.getTimezoneOffset() * 60000)));
eventData[i].CreatedBy = //here i want to add the users emailadress from the token;
dbo.collection('ScheduleData').insertOne(eventData[i]);
}
}
I tried to add the token middleware to the function, like this:
app.post("/BatchData", authRequired, (req, res) => {

but as soon i add that extra argument, it stops retrieving the appointments, without any error message.  This is my authRequired function:

const User = require('../models/user');
const jwt = require('jsonwebtoken');
const config = require('../config/database')

function authRequired(req, res, next) {
const token = req.get("authorization");
if (!token) {
res.json({ success: false, message: "No token provided" });
} else {
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
res.json({ success: false, message: "Token is invalid" + err });
} else {
req.decoded = decoded;
next();
}
});
}
}

module.exports = {
authRequired: authRequired
};

Another option would be to send the emailaddress via the frontend. How do I add a custom field 'createdBy' (without any graphical input elements) to send a value from my component along with the appointment data in the Mongo collection? Do I add that in the onPopUpOpen() function?



Can you maybe help me on how to put users emailadres there at the 'createdBy' field? I retrieve the users info by this code:

ngOnInit() {
this.auth.getProfile().subscribe((profile : any) => {
this.userName = profile.user.username;
this.email = profile.user.email;
console.log(profile.user.email)
})
}

If you need any more info, please let me know

Thanks in advance

Vinitha Devi Murugan [Syncfusion]
Replied On November 20, 2019 10:42 AM UTC

Hi Youssef, 
 
Greetings from Sycfusion Support. 
 
Based on the your requirement, we have prepared a sample to add ‘CreatedBy’ custom field in event window by making use of popupOpen event of scheduler and the same can be downloaded from the following link, 
 
 
  onPopupOpen(args: PopupOpenEventArgs): void { 
    if (args.type === 'Editor') { 
      // Create required custom elements in initial time 
      if (!args.element.querySelector('.custom-field-row1')) { 
        let row: HTMLElement = createElement('div', { className: 'custom-field-row1' }); 
        let formElement: HTMLElement = <HTMLElement>args.element.querySelector('.e-schedule-form'); 
        formElement.firstChild.insertBefore(row, args.element.querySelector('.e-title-location-row')); 
        let container: HTMLElement = createElement('div', { className: 'custom-field-container1' }); 
        let inputEle: HTMLInputElement = createElement('input', { 
          className: 'e-field', attrs: { name: 'CreatedBy' } 
        }) as HTMLInputElement; 
        container.appendChild(inputEle); 
        row.appendChild(container); 
        let inputobj: TextBox = new TextBox({ 
          placeholder: 'CreatedBy', 
        }); 
        inputobj.appendTo(inputEle); 
        inputEle.setAttribute('name', 'CreatedBy'); 
      } 
    } 
  } 
 
Please refer below UG for addition additional fields in default window. 
 
 
 
Serve Image with additional field: 
 
 
 
Network tab image: 
 
 
 
 
Kindly try the above sample, if you have any concerns please revert us back for further assistance. 
 
Regards, 
M.Vinitha devi 


Youssef Lakdime
Replied On November 20, 2019 10:59 AM UTC

Hello Vinitha,

Thank you for your reply. However, i think I did not make my purpose clear, because I dont want another textbox of 'createdBy'. I want the 'createdBy' value to be added automatically from the authenticationService, which grabs the logged in Users' email address.  Like so:

export class ScheduleComponent implements OnInit {

userName;
email;


ngOnInit() {
this.auth.getProfile().subscribe((profile : any) => {
this.userName = profile.user.username;
this.email = profile.user.email;
console.log(profile.user.email)
})
}

I hope i made my point clearer now :). I want to put that email variable into 'createdBy' but that should not be entered in the onPopUpOpen event





Vinitha Devi Murugan [Syncfusion]
Replied On November 21, 2019 08:52 AM UTC

Hi Youssef, 
 
Thanks for your update. 
 
We have achieved your requirement by making use of actionBegin event of our scheduler and for the same we have modified our previously shared sample and the same can be available in below link. 
 
 
  onActionBegin(args: ActionEventArgs): void { 
    if (args.requestType === "eventCreate") { 
      args.data[0].CreateBy = this.email; 
      args.data[0].UserName = this.userName; 
    } 
  } 
 
Server side image: 
 
 
Network tab image: 
 
 
 
Regards, 
M. Vinitha devi 


Youssef Lakdime
Replied On November 21, 2019 02:17 PM UTC

Thank you Vinitha for your reply. I got it working now. However, How do I query the appointments to only show the events of the logged in user?

Like this:
app.post("/GetData", (req, res) => {
debugger;
dbo.collection('ScheduleData').find({'CreatedBy':'testUser'}).toArray((err, cus) => {
res.send(cus);

});
});

But not static 'testUser' but the username that is stored in the a token in localstorage called 'User' . 
I have another method for getting the logged in users profile like this:

router.get('/profile', authRequired, (req, res) => {
User.findOne({_id: req.decoded.userId}).select('username email').exec((err, user) =>{
if(err){
res.json({success: false, message: err});
} else {
if(!user){
res.json({success: false, message: 'Not found'});
} else {
res.json({success: true, user: user})
}
}
});
});

However, if I add the middleware 'authRequired' into the '/getData' endpoint, it stops working. 
How can I retrieve the logged in users email in order to assign that to the find({}) query?





Vinitha Devi Murugan [Syncfusion]
Replied On November 22, 2019 12:01 PM UTC

 
Hi Youssef, 
 
Thanks for your update. 
 
We suspect that your query is wrong, we have modified our previously shared sample to filter and show the particular logged user’s event by using below code.  
 
 
app.post("/GetData", (req, res) => { 
  var query = { CreateBy: /^username@gmail.com/ }; 
  dbo.collection('ScheduleData').find(query).toArray((err, cus) => { 
  res.send(cus); 
  }); 
  } 
 
Kindly try the above solution and let us know, if you need further assistance on this. 
 
Regards, 
M.Vinitha devi 


Youssef Lakdime
Replied On November 24, 2019 07:40 PM UTC

Hi Vinitha, thank you for your update.

However, your code implies that only the events of username@gmail.com (static) will get retrieved, no matter which user is logged in. That was not what I meant. My purpose was to assign the getData query to load all the events of the current logged in users' username.

I have this code in my app.component.ts that loads the username from the auth token:

ngOnInit() {
this.userName = JSON.parse(localStorage.getItem("user"));
console.log(this.userName.username)
this.userName = this.userName.username
}

So how can I query so that 'createdBy' equals this.userName ?

 I hope I made it clearer. Thanks in advance.

Vinitha Devi Murugan [Syncfusion]
Replied On November 25, 2019 09:30 AM UTC

Hi Youssef, 
 
Thanks for your update. 
 
To send an additional custom parameter to the server-side post, you need to make use of the addParams method of query. Now, assign this query object with additional parameters to the query property of Scheduler. We have prepared a below sample to pass tokens as an additional parameter to the scheduler and same can be available in below link.  
 
 
App.component.ts file: 

  ngOnInit(): void { 
    this.selectedDate = new Date(2018, 1, 14); 
    this.email = "username@gmail.com"; // Here we used static email address for your reference. Kindly map your currently logined user email to achieve your scenario. 
    this.userName = "usename"; // Here we used static user name for your reference. Kindly map your currently logined username to achieve your scenario. 
    this.data =  { Name: this.userName, Email: this.email }; 
    this.dataQuery = new Query().addParams('tokens', this.data as any); 
    this.eventSettings = { dataSource: this.dataManager, query: this.dataQuery }; 
  } 

Server.js file: 

    app.post("/GetData", (req, res) => { 
        var query = { CreateBy: req.body.params.tokens.Email }; 
        dbo.collection('ScheduleData').find(query).toArray((err, cus) => { 
            res.send(cus); 
        }); 
    }); 
 
Network tab Image: 
 
 
 
Kindly try the above sample, if you have any concerns please revert us back for further assistance. 
 
Regards, 
M.Vinitha devi 


CONFIRMATION

This post will be permanently deleted. Are you sure you want to continue?

Sorry, An error occured while processing your request. Please try again later.

Please sign in to access our forum

This page will automatically be redirected to the sign-in page in 10 seconds.

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon