Integrating fullcalendar and populating from json

Tips submitted by PHPMaker users
Post Reply
josejad
User
Posts: 109
Location: Spain

Integrating fullcalendar and populating from json

Post by josejad »

Hi:

Here I share a way of adding a fullcalendar.io
Probably there will be better ways of populating the calendar, but I've done with a json custom file.
In my example, I have a table with holydays requests, and they can be 'Accepted', 'Rejected' or 'Pendind review'
Steps
1.- Download the .zip file from h**ps://fullcalendar.io/ and extract the files to a folder. I've extracted to ./phpjs folder (including the locales folder of the zip)
2.- Add a custom file for your calendar (i.e mycalendar.php) and add: (you can add the calendar easily with some options, I will left the options I've used because maybe useful for someone

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset='utf-8' />
//change the folder here to the unzipped files
<script src='phpjs/main.js'></script>
<link href='phpjs/main.css' rel='stylesheet' />
<script src='phpjs/locales/es.js'></script>
<script>
  document.addEventListener('DOMContentLoaded', function() {
	var calendarEl = document.getElementById('calendar');

	var calendar = new FullCalendar.Calendar(calendarEl, {
	  headerToolbar: {
		left: 'prev,next today BtnDenegadas',
		center: 'title',
		right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
	  },
	  navLinks: true, // can click day/week names to navigate views
	  businessHours: true, // display business hours
	  editable: true,
	  selectable: true,
        //I will add a custom button to hide the "rejected holydays"
	customButtons: {
		BtnDenegadas: {
			text: 'Hide Rejected',
			click: function() {
				if (calendar.getEventSourceById('REJECTED')) {
					calendar.getEventSourceById('REJECTED').remove();
				} 			

			}
		}
	},
	// With this option, you can show a modal dialog to edit the event. Be sure to have permissions to edit and select modal in the edit page of your talbe
	eventClick:  function(info) {
		$('#eventUrl').attr('href',ew.modalDialogShow({lnk:this,btn:'AddBtn',url:'solicitud_vacaciones_viewedit.php?id='+info.event.id}));
		},
	  //I will call the same page to get the json, with different parameters (rejected, denied...) to show them in different colors (you can add extraParams)
	  eventSources: [
			// REJECTED
			{
			  url: '/lista_vacaciones.php',
			  type: 'GET',
			  extraParams: {
				autorizacion: 'Accepted',
			  },
			  error: function() {
				alert('ha habido un error leyendo los datos.');
			  },
			  color: '#28A745',   // a non-ajax option
			  textColor: 'white' // a non-ajax option
			},
			
			//PENDING
			{
			  url: '/lista_vacaciones.php',
			  type: 'GET',
			  extraParams: {
				autorizacion: 'PENDING',
			  },
			  error: function() {
				alert('ha habido un error leyendo los datos.');
			  },
			  color: '#FFC107',   // a non-ajax option
			  textColor: 'black' // a non-ajax option
			},

			//DENIED
			{
			  id: 'DENIED',
			  url: '/lista_vacaciones.php',
			  type: 'GET',
			  extraParams: {
				autorizacion: 'Denied',
			  },
			  error: function() {
				alert('ha habido un error leyendo los datos.');
			  },
			  color: '#DC3545',   // a non-ajax option
			  textColor: 'white' // a non-ajax option
			
			}				
			]
		});
		calendar.setOption('locale', 'es');
		calendar.render();
  });
</script>

</head>
<body>

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

</body>
</html>

3.- Ok, now I will create the json events to show in my calendar. My file is called lista_vacaciones.php. It's a custom file
3.1 Create the custom file and add your query

<?php
	// the calendar will call h**p://localhost/lista_vacaciones.php?start=2020-06-28T00%3A00%3A00%2B02%3A00&end=2020-08-09T00%3A00%3A00%2B02%3A00
       //get the start and end date showed  (I don't need hours, etc.. so I get the date substring)
	$from= substr(Get("start"), 0,10);
	$to= substr(Get("end"), 0,10);
   
        //I will add a day to the ending day, because fullcalendario end date is not inclusive, so it's not showed
	$sql = "SELECT `id`, `Operario` AS 'title', `start_date` as 'start', DATE_ADD(end_date, INTERVAL 1 DAY) as 'end' FROM `solicitud_vacaciones_view` WHERE `fecha_inicio` >= '".$desde."' AND `fecha_fin` <= '".$hasta."' AND `autorizacion` LIKE '" . Get("autorizacion") . "'"; 
	 echo $db->ExecuteJson($sql);

 ?>

3.2 After generating the files, you have to remove header and footer from this file.

And I think that's all. I hope it can be helpful to someone.


Neelima
User
Posts: 35

Post by Neelima »

Hi,

You saved the day :)

Thank you very much for posting code

noorshiam
User
Posts: 67
Location: Surabaya - East Java - Indonesia
Contact:

Post by noorshiam »

Hi josejad,

Can you show us solicitud_vacaciones_view structure ?

Thanks before


josejad
User
Posts: 109
Location: Spain

Post by josejad »

Hi:

It's not relevant. It's just if you want to modify some data of any of your tables when you click on the event.

i.e. in my case:
id - INT 11
Name - string
date_start - DATE
date_end - DATE
notes - VARCHAR


josejad
User
Posts: 109
Location: Spain

Post by josejad »

You can check how to use the API to get the json instead of create the events.php (lista_vacaciones.php in my sample) file in this thread: (v2020+)

http://www.hkvforums.com/viewtopic.php? ... ar#p156339

You have to add this line at the end of your custom calendar file to avoid an error as described in this thread:

http://www.hkvforums.com/viewtopic.php?f=4&t=49553

**** Just change "planificacion" to the name of your table

<script>
if (!ew.vars.tables.planificacion) ew.vars.tables.planificacion = <?= JsonEncode(GetClientVar("tables", "planificacion")) ?>;
</script>

ddiaz2380
User
Posts: 134

Post by ddiaz2380 »

@josejad How can I add colors to the events on the calendar? I have a state field which I have 6 states, each one of them I represent them by means of colors in the grind.

// Row Rendering event
function Row_Rendering()
{
    // Enter your code here
	if ($this->Estado->CurrentValue == 1) $this->RowAttrs["style"] = "background-color: #00ec25";
	if ($this->Estado->CurrentValue == 2) $this->RowAttrs["style"] = "background-color: #e2ff49";
	if ($this->Estado->CurrentValue == 3) $this->RowAttrs["style"] = "background-color: #ffb13b";
	if ($this->Estado->CurrentValue == 4) $this->RowAttrs["style"] = "background-color: #ff4d4d";
	if ($this->Estado->CurrentValue == 5) $this->RowAttrs["style"] = "background-color: #000000";		
}

josejad
User
Posts: 109
Location: Spain

Post by josejad »

Hi ddiaz:

  • Add your color property in the sql sentence (i.e.: YourTable.ColorField as color_back,...)
  • Then, in your calendar javascript add:
	  eventDidMount: function(info) {
		// console.log(info.event.title);
		info.event.setProp( 'backgroundColor', info.event.extendedProps.color_back );
	  },

ddiaz2380
User
Posts: 134

Post by ddiaz2380 »

Hi @josejad

the field, "backgroundColor" must it be hex?

I created a Color field which I use the colorpicker, but it doesn't change the colors in the calendar.

<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="utf-8" />
        <link href="plugins/fullcalendar/lib/main.css" rel="stylesheet" />
        <script src="plugins/fullcalendar/lib/main.js"></script>
        <script src="plugins/fullcalendar/lib/locales/es.js"></script>
        <script>
            document.addEventListener("DOMContentLoaded", function () {
                var initialLocaleCode = "es";
                var calendarEl = document.getElementById("calendario");
                var calendar = new FullCalendar.Calendar(calendarEl, {
                    headerToolbar: {
                        left: "prev,next today",
                        center: "title",
                        right: "dayGridMonth,timeGridWeek,timeGridDay,listMonth",
                    },
                    navLinks: true, // can click day/week names to navigate views
                    businessHours: true, // display business hours
                    selectable: true,
                    editable: true,
                    eventClick: function (info) {
                        // Optionally show a modal dialog to edit event on click
                        //$('#eventUrl').attr('href',ew.modalDialogShow({lnk:this,btn:'AddBtn',url:'citacalendarview/'+info.event.id}));
                        $("#eventUrl").attr("href", ew.modalDialogShow({ url: "citacalendarview/" + info.event.id }));
                        info.event.setProp("backgroundColor", info.event.extendedProps.Color);
                        //$('#eventUrl').attr('href',ew.modalDialogShow({lnk:this,btn:'AddBtn',url:'TimeslotsView/'+info.event.id})); // replace "TimeslotsView" by your page to display
                    },
                    events: "api/schedule/events", //This picks up events via JSON calls. You can use other words in place of "events" to convey different requests.
                });
                calendar.setOption("locale", "es");
                calendar.render();
            });
        </script>
    </head>
    <body>
        <div id="calendario"></div>
    </body>
</html>

josejad
User
Posts: 109
Location: Spain

Post by josejad »

Hi ddiaz:

You've set the background into the EventClick.
You have to add an EventMount.
Yes, the colors in hex, ie: #826523

Your code should be something like

            ..........................   
            eventClick: function (info) {
                        // Optionally show a modal dialog to edit event on click
                        //$('#eventUrl').attr('href',ew.modalDialogShow({lnk:this,btn:'AddBtn',url:'citacalendarview/'+info.event.id}));
                        $("#eventUrl").attr("href", ew.modalDialogShow({ url: "citacalendarview/" + info.event.id }));
                        info.event.setProp("backgroundColor", info.event.extendedProps.Color);
                        //$('#eventUrl').attr('href',ew.modalDialogShow({lnk:this,btn:'AddBtn',url:'TimeslotsView/'+info.event.id})); // replace "TimeslotsView" by your page to display
                 },
		eventDidMount: function(info) {
			info.event.setProp( 'backgroundColor', info.event.extendedProps.color_back );
		},
                .............................

btw, I mentioned you in twitter to make you know I had answered the forum after some time.


vuongduongquoc
User
Posts: 133

Post by vuongduongquoc »

I follow the steps but cannot display data in fullcalender. I got this error in line 16 ( echo $db->ExecuteJson($sql));

D:\xampp\htdocs\dxcupgrade\views\Callmycalendar.php(16): Call to a member function ExecuteJson() on null

<?php

namespace PHPMaker2022\dxcupgrade;

// Page object
$Callmycalendar = &$Page;
?>
<?php
	// the calendar will call h**p://localhost/lista_vacaciones.php?start=2020-06-28T00%3A00%3A00%2B02%3A00&end=2020-08-09T00%3A00%3A00%2B02%3A00
       //get the start and end date showed  (I don't need hours, etc.. so I get the date substring)
	$from= substr(Get("start"), 0,10);
	$to= substr(Get("end"), 0,10);
   
        //I will add a day to the ending day, because fullcalendario end date is not inclusive, so it's not showed
	$sql = "SELECT `id`, `title` AS 'title', `start_event` as 'start', `end_event` as 'end' FROM `tbl_nks_events` WHERE `id` = `1`"; 
	 echo $db->ExecuteJson($sql);

 ?>


<?= GetDebugMessage() ?>

===debug===
#0 D:\xampp\htdocs\dxcupgrade\vendor\slim\php-view\src\PhpRenderer.php(203): include()
#1 D:\xampp\htdocs\dxcupgrade\vendor\slim\php-view\src\PhpRenderer.php(184): Slim\Views\PhpRenderer->protectedIncludeScope('views/Callmycal...', Array)
#2 D:\xampp\htdocs\dxcupgrade\vendor\slim\php-view\src\PhpRenderer.php(153): Slim\Views\PhpRenderer->fetchTemplate('Callmycalendar....', Array)
#3 D:\xampp\htdocs\dxcupgrade\vendor\slim\php-view\src\PhpRenderer.php(54): Slim\Views\PhpRenderer->fetch('Callmycalendar....', Array, true)
#4 D:\xampp\htdocs\dxcupgrade\controllers\ControllerBase.php(71): Slim\Views\PhpRenderer->render(Object(Slim\Http\Response), 'Callmycalendar....', Array)
...


ddiaz2380
User
Posts: 134

Post by ddiaz2380 »

josejad wrote:

Hi ddiaz:

You've set the background into the EventClick.
You have to add an EventMount.
Yes, the colors in hex, ie: #826523

Your code should be something like

            ..........................   
            eventClick: function (info) {
                        // Optionally show a modal dialog to edit event on
click
                       
//$('#eventUrl').attr('href',ew.modalDialogShow({lnk:this,btn:'AddBtn',url:'citacalendarview/'+info.event.id}));
                        $("#eventUrl").attr("href",
ew.modalDialogShow({ url: "citacalendarview/" + info.event.id
}));
                        info.event.setProp("backgroundColor",
info.event.extendedProps.Color);
                       
//$('#eventUrl').attr('href',ew.modalDialogShow({lnk:this,btn:'AddBtn',url:'TimeslotsView/'+info.event.id}));
// replace "TimeslotsView" by your page to display
                 },
		eventDidMount: function(info) {
			info.event.setProp( 'backgroundColor',
info.event.extendedProps.color_back );
		},
                .............................

btw, I mentioned you in twitter to make you know I had answered the forum
after some time.

It keeps showing the primary color in all the calendar fields, I even gave the color field the name color_back which saves hex data using the colorpicker.


josejad
User
Posts: 109
Location: Spain

Post by josejad »

Hi:

Sorry, I don't know where's your problem, here you have my full custom file with the calendar, maybe it help you:

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset='utf-8' />
<script src='phpjs/main.js'></script>
<link href='phpjs/main.css' rel='stylesheet' />
<script src='phpjs/locales/es.js'></script>
<script src='https://unpkg.com/popper.js/dist/umd/popper.min.js'></script>
<script src='https://unpkg.com/tooltip.js/dist/umd/tooltip.min.js'></script>
<style>
	[draggable=true] {
	  cursor: move;
	}
	
	.resizable {
  overflow: scroll;
  resize: both;
  max-width: 300px;
  max-height: 460px;
  border: 1px solid black;
  min-width: 50px;
  min-height: 50px;
  background-color: skyblue;
}
	
  .tooltip {
	position: absolute;
   
	background: #FFC107;
	color: black;
	width: 150px;
	border-radius: 3px;
	box-shadow: 0 0 2px rgba(0,0,0,0.5);
	padding: 10px;
	text-align: center;
	opacity: 1;
  }
  
  .tooltip-inner{
	  background-color: transparent;
  }
  


  #external-events {
	position: fixed;
	z-index: 2;
	top: 100px;
	left: 420px;
	width: 180px;
	padding: 0 10px;
	border: 1px solid #ccc;
	background: #eee;
  }

  .demo-topbar + #external-events { /* will get stripped out */
	top: 60px;
  }

  #external-events .fc-event {
	cursor: move;
	margin: 3px 0;
  }

}

</style>
<script>
  document.addEventListener('DOMContentLoaded', function() {
	var calendarEl = document.getElementById('calendar');
	// DESCOMENTAR ESTA PARTE PARA PODER HACER DRAG
	// var Draggable = FullCalendar.Draggable;
	// var containerEl = document.getElementById('external-events');
	// var calendarEl = document.getElementById('calendar');
	// var checkbox = document.getElementById('drop-remove');
	// //Inicializamos los elementos "draggables"
	// new Draggable(containerEl, {
		// itemSelector: '.fc-event',
		// eventData: function(eventEl) {
			// return {
				// title: eventEl.innerText
			// };
		// }
	// });
	var calendar = new FullCalendar.Calendar(calendarEl, {
		initialView: 'dayGridWeek',
		weekNumbers: true,
		eventOrder: 'dni_JdO,title',
		timeZone: 'Europe/Madrid', 
		headerToolbar: {
			left: 'prev,next today BtnDenegadas BtnPlaniDiaria BtnAddPlani',
			center: 'title',
			right: 'dayGridMonth,dayGridWeek,timeGridDay,listMonth'
		},
		navLinks: true, // can click day/week names to navigate views
		businessHours: true, // display business hours
		//editable: true,
		selectable: true,
		//droppable: true, // this allows things to be dropped onto the calendar
		// drop: function(info) {
		// // is the "remove after drop" checkbox checked?
			// if (checkbox.checked) {
			// // if so, remove the element from the "Draggable Events" list
			// info.draggedEl.parentNode.removeChild(info.draggedEl);
			// }
		// },
	  
	customButtons: {
		BtnDenegadas: {
			text: 'Vacaciones',
			click: function() {
				if (calendar.getEventSourceById('Vacaciones')) {
					calendar.getEventSourceById('Vacaciones').remove();
				} 			

			}
		},
		
		
		BtnPlaniDiaria: {
			text: 'Enviar Planificacion',
			click: function() {
				//var respuesta;
				//timeGridDay (diaria), dayGridWeek (semanal)
				//alert(calendar.view.type);
			// switch (calendar.view.type) {
			// case 'timeGridDay':
				// var tipo_plani = "diaria";
				// break;
			  // case 'dayGridWeek':
				// var tipo_plani = "semanal";
				// break;

			  // default:
				//Declaraciones ejecutadas cuando ninguno de los valores coincide con el valor de la expresión
				// break;
			// }
				var fecha_desde = formatDate(calendar.view.activeStart)
				var fecha_hasta = calendar.view.activeEnd.setDate(calendar.view.activeEnd.getDate() - 1);
				var r = confirm("¿Desea enviar la planificación del " + fecha_desde + " al " + formatDate(fecha_hasta) + "?");
				if (r == true) {
					// var hoy = new Date();
					// if (hoy.getDay() == 5) { //es viernes
						// hoy.setDate(hoy.getDate() + 3) //proximo lunes
					// }else {
						// hoy.setDate(hoy.getDate() + 1) //mañana
					// }
					//tomorrow.setDate(tomorrow.getDate() + 1);
					//alert(hoy);
					$.get('PlanificacionEnvio?fecha_desde=' + fecha_desde + '&fecha_hasta=' + formatDate(fecha_hasta));
				} else {
					
				}
				
			}
		},	
		BtnAddPlani: {
			text: 'Añadir plani',
			click: function() {
				var fecha_desde = formatDate(calendar.view.activeStart)
				var fecha_hasta = calendar.view.activeEnd.setDate(calendar.view.activeEnd.getDate() - 1);
				ew.modalDialogShow({lnk:this,btn:'SaveBtn',url:'PlanificacionAdd?modal=1'});
			}
		}
	},
	  eventDidMount: function(info) {
		// console.log(info.event.title);

		  
		if (info.event.extendedProps.description != '' || info.event.extendedProps.description != 'GUARDIA') {
		//	console.log(info.event.title + ' color: ' + info.event.extendedProps.color_back + ' otro: ' + info.event.extendedProps.description);
			info.event.setProp( 'backgroundColor', info.event.extendedProps.color_back );
		}
		var evento = info.event.extendedProps.tipo_evento;
		var dia = info.event.extendedProps.tipo_dia;
		if (evento == 'vacaciones' || (dia != '' && dia != null  && dia != 'GUARDIA'))  {
			//console.log(info.event.extendedProps);
			info.event.setProp( 'backgroundColor', '#000000' );
		}

		var tooltip = new Tooltip(info.el, {
		  title: info.event.extendedProps.description,
		  placement: 'top',
		  trigger: 'hover',
		  container: 'body'
		});
	  },
	  

	  // eventContent: function(arg, createElement) {
		  // var innerText

		  // if (arg.event.extendedProps.description == 'Aguilar Delgado, José Juan') {
			// innerText = '<em class=\'far fa-umbrella-beach\'></em> ' + arg.event._def.title
		  // } else {
			// innerText = '<em class=\'far fa-umbrella-beach\'></em> ' + arg.event._def.title
		  // }

		  // return innerHTML('i', {}, innerText)
		// }, 

	  
	  
	eventClick:  function(info) {
		//alert(info.event.extendedProps.description);
		//alert (user_level);
		//si el JdO edita su propia obra, o no hay asignación, o es la manager quien edita o no tiene tipo_dia asignado
		if (info.event.extendedProps.dni_JdO == var_dni_Jdo || ((info.event.extendedProps.tipo_dia == '' || info.event.extendedProps.tipo_dia == null) && (info.event.extendedProps.dni_JdO == null || info.event.extendedProps.dni_JdO == '')) || user_level == 4 || user_level == 7) {  
			switch (info.event.extendedProps.tipo_evento) {
			  case 'vacaciones':
				$('#eventUrl').attr('href',ew.modalDialogShow({lnk:this,btn:'SaveBtn',url:'SolicitudVacacionesViewedit?id='+info.event.id}));
				break;
			  case 'planificacion':
				ew.modalDialogShow({lnk:'this',btn:'SaveBtn',url:'PlanificacionEdit?id='+info.event.id});
				//window.open('PlanificacionEdit?id='+info.event.id);
				break;
			  default:
				console.log('No hay una opción para ' + info.event.extendedProps.tipo_evento + '.');
			}
		} else {
			if (info.event.extendedProps.JdO == null) {
				alert('Operario ya asignado: ' + info.event.extendedProps.tipo_dia );
			} else {
				alert('Operario ya asignado, contacte con el jefe de obra correspondiente: ' + info.event.extendedProps.JdO );
			}
			//modal.style.display = "block";
		}		
	},
	  

  eventSources: [
		//Vacaciones
			{
			  id: 'Vacaciones',
			  url: '/api/schedule/Vacaciones_Planificacion',
			  type: 'GET',
			  extraParams: {
				evento: 'Vacaciones_Planificacion',
			  },
			  error: function() {
				alert('ha habido un error leyendo los datos.');
			  },
			  color: 'green',   // a non-ajax option
			  textColor: 'red' // a non-ajax option
			},
		//Festivos
			{
			  id: 'Festivos',
			  url: '/api/schedule/Festivos',
			  type: 'GET',
			  extraParams: {
				evento: 'Festivos',
				delegacion: delegacion,
			  },
			  error: function() {
				alert('ha habido un error leyendo los datos.');
			  },
			  display: 'background'
			},
		//Planificación
		{
		  id: 'Planificacion',
		  url: '/api/schedule/Planificacion',
		  type: 'GET',
		  extraParams: {
			evento: 'Planificacion',
			delegacion: delegacion,
		  },
		  error: function() {
			alert('ha habido un error leyendo los datos.');
		  },
		  color: 'gray',   // a non-ajax option
		  textColor: 'white' // a non-ajax option
		  
		}		
	],
	
		eventContent: function (arg) {
		// alert(arg.event._def.description);
		 // if (arg.event._def.extendedProps.tipo_evento == 'vacaciones')
		 var str = arg.event._def.description
		 switch (arg.event._def.extendedProps.tipo_dia) {
			  case 'VACACIONES':
				text = ' <i class=\"fa fa-bed\" aria-hidden=\"true\"></i> '+ arg.event._def.title;
				break;
			  case 'BAJA':
				text = ' <i class=\"fa fa-medkit\" aria-hidden=\"true\"></i> '+ arg.event._def.title;
				break;
			  case 'CURSO':
				text = ' <i class=\"fa fa-graduation-cap\" aria-hidden=\"true\"></i> '+ arg.event._def.title;
				break;
			  case 'FESTIVO':
				text = ' <i class=\"fa fa-hand-peace-o\" aria-hidden=\"true\"></i> '+ arg.event._def.title;
				break;		
			  case 'GUARDIA':
				text = ' <i class=\"fa fa-exclamation-triangle\" aria-hidden=\"true\"></i> '+ arg.event._def.title;
				break;					
			  default:
				text = arg.event._def.title;
				break;
			}
			//console.log(arg.event._def.extendedProps.tipo_evento);
			if (arg.event._def.extendedProps.tipo_evento == 'vacaciones') text = arg.event._def.title + ' (Solicitud vacaciones)';
			  return {
			html: text
		  };

		},
	},
	
	);

		//cargamos la fecha guardada
		if(localStorage.getItem('savedMonth')!=null){
			//console.log(localStorage.getItem('savedMonth'));
			//console.log(formatDate(localStorage.getItem('savedMonth')));
			var fecha = formatDate(localStorage.getItem('savedMonth'));
			calendar.gotoDate( fecha );
		}
		//console.log(calendar.view.currentStart);
		calendar.setOption('locale', 'es');	
		calendar.render();
		//guardamos aquí el mes actual en el evento onclick, ya que si lo ponemos con next y previous no funciona.
		//Buscar el próximo localStorage para los botones siguiente y anterior. Ver
		//https://github.com/fullcalendar/fullcalendar/issues/2939
		calendarEl.querySelector('.fc-today-button').addEventListener('click', function() {
			localStorage.setItem('savedMonth',calendar.view.activeStart);
			//alert('Click');
		});	
  });
  
	function formatDate(date) { //formateamos la fecha start ya que nos daba un error al pasarla a gotoDate
		var d = new Date(date),
			month = '' + (d.getMonth() + 1),
			day = '' + d.getDate(),
			year = d.getFullYear();

		if (month.length < 2) 
			month = '0' + month;
		if (day.length < 2) 
			day = '0' + day;

		return [year, month, day].join('-');
	}
	
// Get the modal
var modal = document.getElementById("myModal");

</script>

</head>
<body>
<a href="javascript:window.print();">Imprimir Calendario</a>
<br /><br />

<!-- DESCOMENTAR ESTA PARTE PARA HACER DRAG DE EVENTOS
<div id='external-events'>
  <p>
	<strong>Jefes de Obra</strong>
  </p>

  <div class='fc-event fc-h-event fc-daygrid-event fc-daygrid-block-event'>
	<div class='fc-event-main'>Agustín Martín</div>
  </div>
  <div class='fc-event fc-h-event fc-daygrid-event fc-daygrid-block-event'>
	<div class='fc-event-main' color='#black'>Manuel Garrido</div>
  </div>
  <div class='fc-event fc-h-event fc-daygrid-event fc-daygrid-block-event'>
	<div class='fc-event-main'>My Event 3</div>
  </div>
  <div class='fc-event fc-h-event fc-daygrid-event fc-daygrid-block-event'>
	<div class='fc-event-main'>My Event 4</div>
  </div>
  <div class='fc-event fc-h-event fc-daygrid-event fc-daygrid-block-event'>
	<div class='fc-event-main'>My Event 5</div>
  </div>

  <p>
	<input type='checkbox' id='drop-remove' />
	<label for='drop-remove'>remove after drop</label>
  </p>
</div>
-->


<div id="card-JdO">
	<div class="card">
		<div class="card-header">
			<a class="card-link" data-toggle="collapse" data-parent="#card-JdO" href="#card-element-1">Jefes de Obra</a>
		</div>
		<div id="card-element-1" class="collapse show">
			<div class="card-body">
				<table class="table table-bordered table-sm">
					<tbody>
						<tr>
						<?php
						//creamos las celcas
						$db =& DbHelper();
						//echo "Responsable: " . CurrentUserId();
						
						$sql = "SELECT CONCAT(apellidos, ', ', nombre) as JdO, codigo_responsable, color FROM `usuarios` WHERE `activo` = 1 AND `delegacion` LIKE 'M502' AND `codigo_responsable` != 'NA'";
						$rs_JdO = $db->ExecuteRows($sql);
						foreach ($rs_JdO as $JdO) {
							echo "<td style='background-color:" . $JdO['color'] . "'>" . $JdO['JdO'] ."</td>";
						}
						?>
							
						</tr>
					</tbody>
				</table>
			</div>
		</div>
	</div>

<script type="text/javascript">
	var var_dni_Jdo = "<?php echo CurrentUserId(); ?>";
	var user_level = "<?php echo CurrentUserLevel(); ?>";
	var delegacion = "<?php echo Profile()->Get('delegacion'); ?>";
	//guardamos la fecha visitada para volver a la misma cuando refresquemos
//	$(document).on('click', '.fc-next-button,.fc-prev-button', function () {
//		localStorage.setItem('savedMonth',calendar.view.activeStart);
		//console.log(localStorage.getItem('savedMonth'));	
//	});
</script>
<div id='calendar'></div>

</body>
<!-- Hay que añadir el siguiente script para que funciionen los lookups en v2021. ver
https://www.hkvforums.com/viewtopic.php?f=4&t=49553&p=163680#p163680
-->
<script>
if (!ew.vars.tables.planificacion) ew.vars.tables.planificacion = <?= JsonEncode(SetClientVar("tables", "planificacion")) ?>;
</script>

WABez
User
Posts: 199

Post by WABez »

eventClick: function (info) {
  $('#eventUrl').attr('href',ew.modalDialogShow({lnk:this,btn:'AddBtn',url:'mytableedit/'+info.event.id}));
}

Would it be possible to add a Delete button to the "edit" modal window, then a user can either edit or delete the event (from this one modal?


Post Reply