I have a calendar where users are going to register reminders and tasks, now I would like each user to see only their own tasks. Each task created is already associated with the user as I will be showing below, for this system I am using Codeigniter + FullCalendar (javascript), it follows my codes and images for better understanding:
Agenda:
View:
<head>
<script type="text/javascript">
$(function(){
$("#nomeEvento").autocomplete({
source: "clientes/get_cliente", // path to the method
appendTo: $("#new_event")
});
});
</script>
<script>
$(function(){
$('.form-control.date').datepicker({
format: 'yyyy-mm-dd',
language: 'pt-BR',
todayHighlight: true
});
});
</script>
<script>
$(document).ready(function() {
$.post('<?php echo base_url();?>calendar2/getEvents',
function(data){
alert(data);
$('#calendar').fullCalendar({
locale: 'pt-br',
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,data){
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){
$('#id').html(event.id);
$('#mtitulo').html(event.title);
$('#autor').html(event.autor);
$('#inicioEdit').val(event.start);
$('#importanciaEdit').val(event.impor);
$('#descricaoEventoEdit').val(event.text);
$('#modalEvento').modal();
},
});
});
});
$(function(){
$('.form-control.date').datepicker({
format: 'yyyy-mm-dd',
language: 'pt-BR',
todayHighlight: true
});
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
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 updateEvents2(){
$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>');
/* Aqui estou definindo as regras de validação do formulário, assim como
na função inserir do controlador, porém estou mudando a forma de escrita */
$this->form_validation->set_rules('mtitulo', 'Nome', 'required|max_length[40]');
$this->form_validation->set_rules('autor', 'Autor', 'trim|required|max_length[100]');
$this->form_validation->set_rules('inicioEdit', 'Data', 'trim|required|max_length[20]');
$this->form_validation->set_rules('importanciaEdit', 'importancia', 'trim|required|max_length[20]');
$this->form_validation->set_rules('descricaoEventoEdit', 'Descricao', 'trim|required|max_length[60]');
/* Executa a validação e caso houver erro chama a função editar do controlador novamente */
if ($this->form_validation->run() === FALSE) {
$this->session->set_flashdata('mensagem', "<div class='alert alert-danger'> preencha todos os campos antes de salvar </div>");
redirect('clientes');
} else
/* Senão obtém os dados do formulário */
$data['idevento'] = $this->input->post('nomeEvento');
$data['nomeEvento'] = $this->input->post('mtitulo');
$data['inicio'] = $this->input->post('inicioEdit');
$data['fim'] = date('Y-m-d', strtotime($this->input->post('inicioEdit'). ' + 1 day'));
$data['user'] = $this->input->post('autor');
$data['importancia'] = $this->input->post('importanciaEdit');
$data['descricaoEvento'] = $this->input->post('descricaoEventoEdit');
/* Executa a função atualizar do modelo passando como parâmetro os dados obtidos do formulário */
if ($this->model->updateEvents2($data)) {
$this->session->set_flashdata('mensagem', "<div class='alert alert-success'> Cliente editado com sucesso</div>");
redirect('clientes');
} else {
$this->session->set_flashdata('mensagem', "<div class='alert alert-danger'> Erro ao editar cliente</div>");
}
}
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->session->set_flashdata('mensagem', "<div class='alert alert-warning'> preencha todos os campos antes de salvar </div>");
redirect('clientes');
/* 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['descricaoEvento'] = $this->input->post('descricaoEvento');
/* Chama a função inserir do modelo */
if ($this->model->inserir($data)) {
$this->session->set_flashdata('mensagem', "<div class='alert alert-success'> Lembrete salvo com sucesso</div>");
redirect('clientes');
} else {
$this->session->set_flashdata('mensagem', "<div class='alert alert-danger'> Erro ao salvar Lembrete </div>");
redirect('clientes');
}
}
}
}
Model:
<?php
class calendar2Model extends CI_Model {
function __construct() {
parent::__construct();
}
public function get_events(){
$this->db->select('idevento id, inicio start, fim end,descricaoEvento text, user autor,importancia impor ,cnome title');
$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;
}
}
}
Related
My real problem is that I am sending an Ajax Jquery Request to an API of mine, the server response is 'Argument #1 of ::setDate() must be DateTimeInterface, string given'
I tried to cast but it was useless.
My Ajax at JQUERY:
$.ajax({
type: "PUT",
url: "/api/distribucion",
data: JSON.stringify(dist),
dataType: "json",
success: function (response) {
console.log("mesa " + response.id + " actualizada");
}
});
My API at PHP (Symfony's controller):
public function putDistribucion(ManagerRegistry $mr, Request $request): Response
{
$datos = json_decode($request->getContent());
$datos = $datos->distribucion;
// Cogemos el ID de el Distribucion a editar
$id = $datos->id;
// Obtenemos el Distribucion
$distribucion = $mr->getRepository(Distribucion::class)->find($id);
// Cambiamos todos sus campos
$distribucion->setPosicionX($datos->pos_x);
$distribucion->setPosicionY($datos->pos_y);
$distribucion->setFecha($datos->fecha);
$distribucion->setMesaId($datos->mesa_id);
$distribucion->setAlias($datos->alias);
$distribucion->setReservada($datos->reservada);
$manager = $mr->getManager();
try {
// Lo mandamos a actualizar
$manager->persist($distribucion);
$manager->flush();
} catch (PDOException $e) {
$this->json(['message' => $e->getMessage(), "Success" => false], 400);
}
# Creado con éxito => Devolvemos la ID
return $this->json(
[
"message" => "Éxito al editar la distribucion " . $id,
"Success" => true
],
202 // Aceptado
);
}
The Object I'm sending:
Your entity Distribucion probably has a setter that look like this:
public function setFecha(DateTimeInterface $fecha): self
{
$this->fecha = $fecha;
return $this;
}
The setter is typehinted with DateTimeInterface so you need to use a DateTime object and not a string.
You may create a DateTime easily with DateTime::createFromFormat
So $distribucion->setFecha($datos->fecha); will turn into something like:
$distribucion->setFecha(DateTime::createFromFormat('YYYY-MM-DD HH:ii:ss.u', $datos->fecha));
You may want to verify the date format I used as the first parameter of DateTime::createFromFormat
public static DateTime::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null)
When I try to use the .pipe() function in my controller I get an error and I don't know why. Attached my code below, thank you very much for the help in advance
const fs =require('fs');
module.exports={
inputs:{
name_file:{
type:"string",
required:true
}
},
exits: {
success: {
description: "Return matching data.",
},
defaultError: {
description: "It catches any error.",
responseType: "defaultError",
},
},
fn:function (inputs,exits){
//Comprobamos si el fichero viene en la peticion
if (!inputs.name_file) return exits.defaultError("No se ha adjuntado el nombre del archivo")
var nameFile=inputs.name_file
//Creamos ruta completa del fichero
var URL_FILE=process.cwd()
URL_FILE= URL_FILE.concat("\\.tmp\\uploads\\",nameFile,'.csv')
//Comprobamos si el fichero existe
fs.access(URL_FILE,fs.constants.F_OK,(err)=>{
return "El fichero no existe"
})
var response={}
var SkipperDisk = require('skipper-disk');
var fileAdapter = SkipperDisk(/* optional opts */);
// Stream the file down
var filedown=fileAdapter.read(URL_FILE)
filedown.on('error', function (err){
return exits.defaultError(err);
})
filedown.on('line',(linea)=>{
console.log(linea)
})
filedown.pipe(exits.success(response))
}
}
TypeError: Cannot read property 'on' of undefined```
hi guys i am working on forget password in mobile app using nativescript, and i want to show alert message when the user insert wrong email or wrong apssword in the dialog , but i couldn't make it is there any body can help ?
let options: PromptOptions = {
title: "Entrez votre nouveau mot de passe",
okButtonText: "Suivant",
cancelButtonText: "Annuler",
cancelable: true,
inputType: inputType.password,
capitalizationType: capitalizationType.none
}; prompt(options).then((pass: PromptResult) => {
if (pass.text && pass.result == true) {
let options: PromptOptions = {
title: "Entrez votre nouveau mot de passe de nouveau",
okButtonText: "Suivant",
cancelButtonText: "Annuler",
cancelable: true,
inputType: inputType.password,
capitalizationType: capitalizationType.none
}; prompt(options).then((pass2: PromptResult) => {
if (pass2.text && pass2.result == true) {
if (pass.text == pass2.text) {
this.auth.resetMDP(this.email, this.code, pass2)
.then((res: any) => {
if (res.message == 'OK')
alert('votre mot de passe a été changé avec succès')
}).catch((err: any) => { alert(err); })
} else alert("re-entrez le mot de passe correctement s'il vous plait");
}
})
}
});
because i ve tried to make it work , but the dialog always close
In my apps I use modals to handle custom dialog styling and special action (as you require validation without closing the dialog). The easiest is:
This is how you call it:
page.showModal(
"you/path/to/modal/directory",
{
// your binding context
},
() => {
// on close callback
}
);
Assume that you have modal layout as XML and code behind (in my case Typescript):
<Page xmlns:RL="nativescript-ripple" xmlns="http://schemas.nativescript.org/tns.xsd" shownModally="onShownModally" >
<DockLayout stretchLastChild="false">
<Label dock="top" text="Hello Modal!!" horizontalAlignment="center" />
<TextView dock="top" text="{{ message }}" fontSize="15sp" horizontalAlignment="left" />
<Button dock="bottom" text="OK" tap="onOkTap" />
</DockLayout>
let closeCallback: () => void;
export function onShownModally(args: any) {
const page: Page = <Page>args.object;
const context = args.context;
// your close callback logic that you passed
closeCallback = args.closeCallback;
// bind you context object to modal
page.bindingContext = fromObject(context);
}
export function onOkTap(args: EventData) {
const page = args.object as Page;
if (closeCallback !== null && closeCallback !== undefined) {
closeCallback();
} else {
page.closeModal();
}
}
I'm using the below JS to feed options for my select:
//**** Instance des Bootstrap-SelectPicker ****
$('.selectpicker').selectpicker({
style: 'btn-info',
size: 4,
showSubtext: true,
noneSelectedText: 'Pas de sélection',
showSubtext: true,
showTick: true,
});
var menus = [
{ controleur: "CatDdeurs", element: "Cat_Ddeur" },
{ controleur: "Communautes", element: "Communaute" },
{ controleur: "Occupations", element: "Occupation" },
{ controleur: "Provinces", element: "Province" },
{ controleur: "Scolarites", element: "Scolarite" },
{ controleur: "Sexes", element: "Sexe" },
{ controleur: "Situations_Matrimoniales", element: "SituationMatrimoniale" },
{ controleur: "Source_De_Revenus", element: "SrceRevenu" },
{ controleur: "Statuts_Legaux", element: "StatutLegal" },
{ controleur: "Tranche_Revenu", element: "TrancheRevenu" },
{ controleur: "Villes", element: "Ville" },
{ controleur: "Sources_Informations", element: "SceInfo" },
{ controleur: "Langues", element: "langMaternelle" },
{ controleur: "Langues", element: "LangAutre" },
{ controleur: "Conseillers", element: "Conseiller" },
];
menus.forEach(x => {
MenusDeroulants('GetListe' + x.controleur, $('#cbx_' + x.element));
});
//**** Permet de remplir la liste des menus déroulants ****
function MenusDeroulants(url, dropdown) {
$.getJSON(url, function (data) {
dropdown.empty();
for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
var prenom;
var nom;
var ID;
//**** Traitement des demandeurs ou conseillers ****
if (url == "GetListeConseillers" || url == "GetListeDemandeurs") {
//**** Retrait du code ****
if (key == 'Code_Conseiller' || key == 'Code_Demandeur') {
ID = obj[key];
};
//**** Retrait du Nom ****
if (key == 'Nom_Conseiller' || key == 'Nom_Demandeur') {
//if (key.match(/Nom_C*/) || key.match(/Nom_D*/)) {
nom = obj[key];
};
//**** Retrait du Prénom ****
if (key == 'Prenoms_Conseiller' || key == 'Prenoms_Demandeur') {
prenom = obj[key];
};
} else { //**** Traitement des autres menus ****
//**** Retrait de l'ID ****
if (key.match(/ID_*/)) {//**** Traitement des demandeurs ou conseillers ****
ID = obj[key];
};
//**** Retrait du Nom ****
if (key.match(/Nom_*/)) {
nom = obj[key];
};
};
}
//**** On construit les options du menu déroulant ****
if (url == "GetListeConseillers" || url == "GetListeDemandeurs") {
dropdown.append($("<option></option>").attr("value", ID).text(nom).attr("data-subtext", prenom));
} else {
dropdown.append($("<option></option>").attr("value", ID).text(nom));
};
if ((nom.toUpperCase() == "CHICOUTIMI" && url == 'GetListeVilles')
|| (nom.toUpperCase() == "QUÉBEC" && url == 'GetListeProvinces')
|| (nom.toUpperCase() == "NON DISPONIBLE" && url != 'GetListeVilles' && url != 'GetListeProvinces')) {
dropdown.prop("selectedIndex", i);
};
}
dropdown.selectpicker('refresh');
});
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>
<td style="padding-left:10px">
<div class="form-group">
<label for="cbx_Sexe" class="control-label">Sexe:</label>
<div>
<select class="selectpicker" id="cbx_Sexe"></select>
</div>
</div>
</td>
The first 12 elements will work fine but as soon as I add the 3 last, my selects will start behaving funny: The 3 lasts will sometimes work fine and some times show a white space on top of the box.
Sometimes, menus will not close when I open others... and so on.
I have tried combining the 12 first with each of the 3 lasts but there will always be something.
More strange is that if I use let say : "{ controleur: "Sexes", element: "Sexe" }," to fill all 3 that are giving me issue, all works perfectly.
Below is a screenshot of the display I'm getting:
Changing my function (MenusDeroulants) parameter dropdown to $dropdown finally solved the issue.
With Blueimp / Jquery File Upload, I can going to preview :
done: function (e, data) {
var file = data.files[0];
console.log(data.files[0]);
console.log(data.result.files); // always undefined ...
$(this).closest('tr').find('input[type=text]').val(file.name.substr(0, file.name.lastIndexOf('.')));
$(this).remove();
},
Return :
Blob { name: "IMG_20160512_225352.jpg", preview: canvas, size: 221398, type: "image/jpeg" }
But, If I added "add" options, I don't have preview :
add: function (e, data) {
var goUpload = true;
var file = data.files[0];
if (!(/\.(gif|jpg|jpeg|png)$/i).test(file.name)) {
$(this).closest('tr').find('td:first').prepend('<div class="alert alert-danger text-justify"><ul class="list-unstyled"><li><span class="glyphicon glyphicon-exclamation-sign"></span> Seuls les types de fichiers suivants sont autorisés : .gif ; .jpg ; .jpeg ; .png</li></ul></div>');
goUpload = false;
}
if (file.size > 2000000) {
$(this).closest('tr').find('td:first').prepend('<div class="alert alert-danger text-justify"><ul class="list-unstyled"><li><span class="glyphicon glyphicon-exclamation-sign"></span> La taille maximale autorisée par fichier est de 2 Mo</li></ul></div>');
goUpload = false;
}
if (goUpload === true) {
data.submit();
}
},
done: function (e, data) {
var file = data.files[0];
console.log(data.files[0]);
console.log(data.result.files); // always undefined ...
$(this).closest('tr').find('input[type=text]').val(file.name.substr(0, file.name.lastIndexOf('.')));
$(this).remove();
},
Return :
File { name: "IMG_20160512_225352.jpg", lastModified: 1463086668000, lastModifiedDate: Date 2016-05-12T20:57:48.000Z, size: 1034928, type: "image/jpeg" }
Can you help me ? I want to going to preview for print him.
Full JS code :
$('.file_upload:last').fileupload({
dataType: 'json',
url: '/app_dev.php/_uploader/gallery/upload',
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator && navigator.userAgent),
imageMaxWidth: 1200,
imageMaxHeight: 1200,
previewMaxWidth : 350,
previewMaxHeight : 350,
imageCrop: false,
autoUpload: true,
/*
add: function (e, data) {
var goUpload = true;
var file = data.files[0];
if (!(/\.(gif|jpg|jpeg|png)$/i).test(file.name)) {
$(this).closest('tr').find('td:first').prepend('<div class="alert alert-danger text-justify"><ul class="list-unstyled"><li><span class="glyphicon glyphicon-exclamation-sign"></span> Seuls les types de fichiers suivants sont autorisés : .gif ; .jpg ; .jpeg ; .png</li></ul></div>');
goUpload = false;
}
if (file.size > 2000000) {
$(this).closest('tr').find('td:first').prepend('<div class="alert alert-danger text-justify"><ul class="list-unstyled"><li><span class="glyphicon glyphicon-exclamation-sign"></span> La taille maximale autorisée par fichier est de 2 Mo</li></ul></div>');
goUpload = false;
}
if (goUpload === true) {
data.submit();
}
},
*/
done: function (e, data) {
var file = data.files[0];
console.log(data);
console.log(data.files[0]);
console.log(data.result.files);
$(this).closest('tr').find('input[type=text]').val(file.name.substr(0, file.name.lastIndexOf('.')));
$(this).remove();
},
progressall: function (e, data) {
var input_this = this;
var progress = parseInt(data.loaded / data.total * 100, 10);
$(input_this).closest('tr').find('.upload-progress .progress-bar-current').text(progress + '%');
$(input_this).closest('tr').find('.upload-progress .progress-bar-current').css(
'width',
progress + '%'
);
},
fail: function(e, data) {
var input_this = this;
$(input_this).closest('tr').html('<td colspan="3" class="text-center background-orange"><i class="fa fa-exclamation-circle"></i> Erreur lors du transfert du fichier, veuillez vérifier qu\'il soit conforme (notamment types de fichiers autorisés, taille maximale)</td>');
}
});
});