简体   繁体   中英

ID of an event (Fullcalendar)

I need add an id to every single event from Fullcalendar, I found this http://arshaw.com/fullcalendar/docs/event_data/Event_Object/ but I don't know how, this id is
unique for every single event, because then I save the events in a Mysql database. Thanks

I found the solution! When you create any event, put your uniqe id here :

var shift = calendar.fullCalendar('renderEvent',
        {
            id: shift_id,
            title: current_name,
            start: new Date(y, m, d + current_day, current_start_time_h, current_start_time_m),
            end: new Date(y, m, d + current_day, current_end_time_h, current_end_time_m),
            allDay: false
        }, true // make the event "stick"
        );

After that this listener append ID in DOM structure:

     eventAfterRender:function( event, element, view ) { 
$(element).attr("id","event_id_"+event._id);
},

To get all your events on a field:

console.log(calendar.fullCalendar('clientEvents'));

Now you have array of events, and all event are numbered in DOM structure!

As fletch mentions, you have to generate the ID for each new event in the DB or with the DB connection code in order to allow for concurrency. Bryan Villafañe uses similar approach, but here is my solution.

For FC javascript:

select: function(start) { //executed when clicked on a day
    var title = prompt('Event title:');
    if (title) {
        $.ajax({
            url: '/events.php',
            data: 'title='+title+'&start='+moment(start).format('YYYY-MM-DD'),
            type: "POST",
            success: function(id) { 
                console.log(id); //used for debug
                if (!isNaN(id)){ //on success checks the result 
                    event = {    //and adds the event locally with the returned DB id.
                        title: title,
                        start: start,
                        team: team,
                        id: id
                    }//then renders the new event
                    $('#calendar').fullCalendar('renderEvent', event, true);
                }
            },
            error: function(error){
                console.log(error);
            }
        });
    } //unselects the clicked day
    $('#calendar').fullCalendar('unselect');
}

This sends the date as a YYYY-MM-DD format since I only use allDay events, but you can update appropriately. Sending just start will result in epoch time with milliseconds.

The DB returns the ID of the row if the insert was successful, which is then assigned to the locally created event and is rendered. Here is the DB function:

$result = "Wrong parameter combination!";
if ($_POST[title]&&$_POST[start]) {
    $result = $db->exec("INSERT INTO events (title, start) VALUES ('$_POST[title]','$_POST[start]')");
    if($result==1){
        $result = $db->lastInsertRowID();
    }
}
echo $result;

Here I check for the two POST parameters and do the insert. If the insert was successful I get the last insert row ID and return it to the JS. Otherwise a error message is returned.

I'm using SQLite3 for my DB but the last inserted row for MySQL can be checked as shown here . There is a small chance for someone to insert another event between your insert and last row ID check, but unless you're running high traffic affair, you'll be OK.

The ID on an Event object is an optional field. You can return and use whatever you'd like to return from your server-side script. You can create a composite ID from a combination of fields...'calendarName_eventID' or simply use an eventID from your database. Not sure you want to expose your primary key like that, though (that's another issue in itself). Long story short...you get to create your own ID value.

You might want to have a look here: https://code.google.com/p/fullcalendar/issues/detail?id=713

The thread deals with deleting a calendar event, but illustrates how the original poster was setting the ID on a callback from his/her save event.

Hope that's helpful.

OK, here is my solution way. first I get the last id event from my DB and i plus 1 to the last id

<?php
$sql = mysql_query("SELECT id FROM calendar ORDER BY id DESC LIMIT 1");

$resul = mysql_fetch_row($sql);
$idActual = $resul[0];
$idActual = $idActual + 1;
?>

then i send the id to JS

var idActual = "<?php echo $idActual ?>";

and that's it.

Clear Solution is

When you fetch events with Ajax also assign "id" that coming from DB

id:entry.id

$.ajax({ 
    url: '/eventsJson', 
    type: 'GET', 
    data: { }, 
    error: function() {
        alert('there was an error while fetching events!');
    } 
}).done(function (doc) { 

    var event = Array();
    $.each(doc, function(i, entry) {
        event.push({id:entry.id, title: entry.title, start: entry.start});
    });

Event Click

eventClick: function(event, jsEvent, view) {
               var title = prompt('Event Title:', event.title, { buttons: { Ok: true, Cancel: false} });

           if (title){
           event.title = title;

           var data = {
                'title':title
            };

           $.ajax({
             url: '/events/'+event.id,
             data: data,
             type: 'POST',
             dataType: 'json',
             success: function(response){
               if(response.status == 'success')
               $('#calendar').fullCalendar('updateEvent',event);
             },
             error: function(e){
               alert('Error processing your request: '+e.responseText);
             }
           });
           }
        }

Each event already has its own unique id:

eventClick: function(event){
    alert(event._id);
}

I recommend you to set the param id in the prameters similar to this one:

 $('#calendar').fullCalendar({ id: 'calendar', eventReceive: function(event) { alert(this.calendar.options.id); }, eventDrop: function(event) { alert(this.calendar.options.id); }, eventClick: function(event) { alert(this.calendar.options.id); }, eventRender: function(event) { alert(this.calendar.options.id); } });

setProp is recommended since v5 hope this helps someone else, I realised it was changing the id within the arg.event._def.id attr.

i used this in my ajax success as so;

          success: function (response_data) {
        arg.event.setProp("id", response_data['eventId'])}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM