使用EventClick完整日历返回数据

时间:2017-05-26 10:30:09

标签: javascript php jquery fullcalendar

大家下午好,我需要帮助,我正在使用Fullcalendar创建一个简单的日历,我已经可以创建事件将它们保存在数据库中并将它们显示在日历中,现在我需要的是点击时事件弹出窗口(Modal)打开显示事件的数据以及执行更新此数据的选项,我已经在模式工作时点击它打开的事件我不知道是如何显示BD中保存的数据在各自的字段中以下是我的代码:

的Controler(calendar2.php):

class Calendar2 extends CI_controller{

    function __construct(){
        parent:: __construct();
        $this->load->model('calendar2Model', 'model', TRUE);
    } 

    public function index(){
        $this->template->set('title', 'Agenda');
        $this->template->load('layout', 'calendar_v.php');
        //$this->load->view('calendar_v.php');
    }

    public function getEvents(){
        $data = $this->model->get_events();
        echo json_encode($data);
    }

    public function updateEvents(){
        $param['id'] = $this->input->post('id');
        $param['inicio'] = $this->input->post('inicio');
        $param['fim'] = $this->input->post('fim');
        $r =  $this->model->updateEvents($param);
        echo json_encode($r);
    }

    public function deleteEvents(){
        $id = $this->input->post('id');
        $r = $this->model->deleteEvents($id);
        echo json_encode($r);
    }

    public function new_event(){

        $this->template->set('title', 'Nova tarefa');

        $this->load->library('form_validation');

        /* Define as tags onde a mensagem de erro será exibida na página */
        $this->form_validation->set_error_delimiters('<span>', '</span>');

        /* Define as regras para validação */
        $this->form_validation->set_rules('nomeEvento', 'Nome', 'required|max_length[40]');
        $this->form_validation->set_rules('inicio', 'Data de inicio', 'trim|required|max_length[60]');
        $this->form_validation->set_rules('importancia', 'Prioridade', 'trim|required|max_length[60]');
        $this->form_validation->set_rules('descricaoEvento', 'descricaoEvento', 'trim|required|max_length[150]');

        /* Executa a validação e caso houver erro chama a função index do controlador */
        if ($this->form_validation->run() === FALSE) {

            $this->template->load('layout', 'clientes_inserir.phtml');
            /* Senão, caso sucesso: */
        } else {

            /* Recebe os dados do formulário (visão) */
            $data['nomeEvento'] = $this->input->post('nomeEvento');
            $data['inicio'] = $this->input->post('inicio');
            $data['fim'] = date('Y-m-d', strtotime($this->input->post('inicio'). ' + 1 day'));
            $data['user'] = $this->input->post('user'); 
            $data['importancia'] = $this->input->post('importancia');   
            $data['importancia'] = $this->input->post('descricaoEvento');   


            /* Chama a função inserir do modelo */
            if ($this->model->inserir($data)) {
                $this->session->set_flashdata('mensagem', 'registro salvo com sucesso');
                redirect('clientes');
            } else {
                $this->session->set_flashdata('mensagem', 'registro nao salvo');
            }

        }
    }

}

模态(calendar2model.php):

<?php

class calendar2Model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    public function get_events(){
        $this->db->select('idevento id,cnome title, inicio start, fim end');
        $this->db->from('eventos');
        $this->db->join('clientes','clientes.ccod = eventos.nomeEvento');

        return $this->db->get()->result();

    }   

    function inserir($data) {
        return $this->db->insert('eventos', $data);
    }

    function updateEvents($param) {
        $campos = array(

                'inicio' => $param['inicio'],
                'fim' => $param['fim']
            );

        $this->db->where('idevento', $param['id']);
        $this->db->update('eventos', $campos);

        if($this->db->affected_rows() == 1){
            return 1;
        } else{
            return 0;
            }       
        }

    function deleteEvents($id){
        $this->db->where('idevento', $id);
        $this->db->delete('eventos');
        if($this->db->affected_rows() == 1){
            return 1;
        } else{
            return 0;
            }       
        }
}

查看(calendar_v.php):

<head>
<div class="row" >
    <div class="col-sm-2">
        <a data-toggle="modal" data-target="#new_event" class="btn btn-primary">Nova Tarefa</a>
    </div>
</div>

<script>



$(document).ready(function() {

  $.post('<?php echo base_url();?>calendar2/getEvents', 
  function(data){
  //alert(data);

    $('#calendar').fullCalendar({
      header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,basicWeek,basicDay'
      },
      defaultDate: new Date(),
      navLinks: true, // can click day/week names to navigate views
      editable: true,
      eventLimit: true, // allow "more" link when too many events
      editable: true,
      events: $.parseJSON(data),

      eventDrop: function(event, delta, revertFunc){
        var id = event.id;
        var fi = event.start.format();
        var ff = event.end.format();

        $.post("<?php echo base_url();?>calendar2/updateEvents",
        {
          id:id,
          inicio:fi,
          fim:ff,
        },
        function(data){
          if(data == 1){
            alert('Evento atualizado');
          }else{
            alert('Evento Nao atualizado')
          }
        });    
      },

      eventResize: function(event, delta, revertFunc) {
        var id = event.id;
        var fi = event.start.format();
        var ff = event.end.format();

        $.post("<?php echo base_url();?>calendar2/updateEvents",
        {
          id:id,
          inicio:fi,
          fim:ff,
        },
        function(data){
          if(data == 1){
          //alert('Evento atualizado');
        }else{
         // alert('Evento não atualizado')
        }

        });  
      },

      // eventClick: function(event,jsEvent, view){
      //   $('#calendar').fullCalendar('removeEvents',event.id);
      //  }

      eventRender: function(event, element){
        var el = element.html();
        element.html("<div style='width:90%;float:left;'>" + el + "</div><div class='closeee' style='color:red; text-align:right;'>X</div>");

        element.find('.closeee').click(function(){
          if(!confirm("Excluir registro ??")){
            revertFunc();
          }else{
                var id = event.id
                $.post("<?php echo base_url();?>calendar2/deleteEvents",
                {
                  id:id,
                },
                function(data){
                  if(data == 1){
                    $('#calendar').fullCalendar('deleteEvents', event.id);
                  //alert('Tarefa Excluida');
                }else{
                 //alert('Tarefa não Excluida')
                }

                }); 
              }
          });
      },

      eventClick: function(event, jsEvent, view){
        $('#mtitulo').html(event.title);
        $('#autor').val(event.id);
        $('#modalEvento').modal();
      },

    });
  });
});

</script>

</head>


<body>

    <div id='calendar'></div>

</body>


<!-- Modal visualizar-->

<div class="modal fade" id="modalEvento" tabindex="-1" role="dialog" aria-labelledby="mymodelLabel">
  <div class="modal-dialog" role="document">
  <div class="modal-content">
    <div class="modal-header bg-red">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <h4 class="modal-title" id="mymodelLabel"> Editar Evento</h4>
    </div>

    <div class="modal-body">

      <div class="row">
        <div class="form-group col-md-6">
            <label for="nomeEvento">Nome Cliente</label> 
          <div class="form-control" id="mtitulo"></div>
        </div>  

        <div class="form-group col-md-6">
          <label for="user">Responsavel</label> 
          <div class="form-control" id="autor"></div>
        </div>
      </div> 

      <div class="row"> 
        <div class="form-group col-md-6">
          <div class="input-group date">
            <input type="text" class="form-control date" id="inicio" name="inicio"/>
            <div class="input-group-addon">
              <span class="glyphicon glyphicon-th"></span>
            </div>
          </div>
        </div>

        <div class="form-group col-md-6">
            <label for="importancia">Prioridade</label> 
            <input type="text" class="form-control" id="importancia" name="importancia"/>
        </div>
      </div>

       <div class="row"> 
        <div class="form-group col-md-12">
          <label for="descricaoEvento">Descrição</label> 
          <input type="text" class="form-control" id="descricaoEvento" name="descricaoEvento"/>
        </div> 
       </div>

    </div>

    <div class="modal-footer">
      <button type="button" class="btn btn-default" id="closeM" data-dismiss="modal">Cancelar</button>
      <button type="button" class="btn btn-danger" id="btnGuardar">Guardar</button>
    </div>
    </div>
  </div>
</div>
<!-- /.modal -->

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以添加eventRender并附加一个onClick监听器,如下所示:

$('#calendar').fullCalendar({
      header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,basicWeek,basicDay'
      },
      [cut]
      eventRender: function (event, element, view) {
            element.attr('href', 'javascript:void(0);');
            element.click(function() {
                    $.get( "yoururl/" + event.id, function( data ) {
                        //Clone object in order to not update the original event (if user press cancel)
                        var eventClone = deepClone(event);
                        eventClone.start = data.myStart;
                        eventClone.end = data.myEnd;
                        eventClone.title = data.myTitle;
                        openDialog(eventClone);
                    });
                });
        }
      [cut]
});

function openDialog(event){
    $('#myForm').modal('show');
    $('#myModalLabel').html(event.title);
    $('#myId').val(event.id);
    [cut]
}

因此,在您保存按钮(在模式对话框中)中,您可以将数据发送到服务器,保存到数据库,然后刷新日历,如:

$('#calendar').fullCalendar( 'refetchEvents' );

我希望很清楚,再见。

答案 1 :(得分:0)

您可以添加以下代码:

  var calendar = $('#calendar').fullCalendar({
     buttonText: {
        prev: '<i class="icon-chevron-left"></i>',
        next: '<i class="icon-chevron-right"></i>'
    },

    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    events: jQuery.parseJSON(data),

    disableDragging: true, 
    editable: true,
    droppable: true, // this allows things to be dropped onto the calendar !!!
    drop: function(date, allDay) { // this function is called when something is dropped

        // retrieve the dropped element's stored Event Object
        var originalEventObject = $(this).data('eventObject');
        var $extraEventClass = $(this).attr('data-class');


        // we need to copy it, so that multiple events don't have a reference to the same object
        var copiedEventObject = $.extend({}, originalEventObject);

        // assign it the date that was reported
        copiedEventObject.start = date;
        copiedEventObject.allDay = allDay;
        if($extraEventClass) copiedEventObject['className'] = [$extraEventClass];

        // render the event on the calendar
        // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
        $('#calendar').fullCalendar('renderEvent', copiedEventObject, true);

        // is the "remove after drop" checkbox checked?
        if ($('#drop-remove').is(':checked')) {
            // if so, remove the element from the "Draggable Events" list
            $(this).remove();
        }

    }
    ,
    selectable: true,
    selectHelper: true,
    select: function(start, end, allDay) {

        bootbox.prompt("New Event Title:", function(title) {
            if (title !== null) {
                calendar.fullCalendar('renderEvent',
                    {
                        title: title,
                        start: start,
                        end: end,
                        allDay: allDay
                    },
                    true // make the event "stick"
                );
            }
        });


        calendar.fullCalendar('unselect');

    }
    ,
    eventClick: function(calEvent, jsEvent, view) {

        var form = $("<form class='form-inline'><label>Change event name &nbsp;</label></form>");
        form.append("<input autocomplete=off type=text value='" + calEvent.title + "' /> ");
        form.append("<button type='submit' class='btn btn-small btn-success'><i class='icon-ok'></i> Save</button>");

        var div = bootbox.dialog(form,
            [
            {
                "label" : "<i class='icon-trash'></i> Delete Event",
                "class" : "btn-small btn-danger",
                "callback": function() {
                    calendar.fullCalendar('removeEvents' , function(ev){
                        return (ev._id == calEvent._id);
                    })
                }
            }
            ,
            {
                "label" : "<i class='icon-remove'></i> Close",
                "class" : "btn-small"
            }
            ]
            ,
            {
                // prompts need a few extra options
                "onEscape": function(){div.modal("hide");}
            }
        );

        form.on('submit', function(){
            calEvent.title = form.find("input[type=text]").val();
            calendar.fullCalendar('updateEvent', calEvent);
            div.modal("hide");
            return false;
        });

    }
});

添加bootbox.min.js以打开弹出窗口。

我希望它对你有用!