I'm using Symfony 5 and Doctrine 2.
When I use the ajax call below described I get this error :
App\Entity\Calendar object not found by the #ParamConverter
annotation.
However, I don't use parameter for my route.
There is my ajax function :
var url = Routing.generate('calendar.ajaxEditEvent');
$.ajax({
type: "POST",
url: url,
data: {
title: e.event.title,
description: e.event.extendedProps.description,
start: e.event.start,
end: e.event.end,
backgroundColor: e.event.backgroundColor,
borderColor: e.event.borderColor,
textColor: e.event.textColor,
allDay: e.event.allDay,
calendarId: e.event.id
}
,
dataType: 'json',
async: true,
sucess: function(reponse){
console.log('success');
console.log(response);
},
error : function(response) {
console.log('error');
console.log(response);
}
});
And my calling function in my controller :
/**
* #Route("/ajaxEditEvent", options={"expose"=true}, name="calendar.ajaxEditEvent", methods={"POST"})
*
* #param CalendarRepository $calendarRepository
* #param Request $request
* #param EntityManagerInterface $manager
*
* #return Response
*/
public function ajaxEditEvent(CalendarRepository $calendarRepository, Request $request, EntityManagerInterface $manager): Response
{
$title = $request->get('title');
$description = $request->query->get('description');
$start = $request->query->get('start');
$end = $request->query->get('end');
$backgroundColor = $request->query->get('backgroundColor');
$borderColor = $request->query->get('borderColor');
$textColor = $request->query->get('textColor');
$allDay = $request->query->get('allDay');
$calendarId = $request->query->get('calendarId');
if(
!empty($title) &&
!empty($description) &&
!empty($start) &&
!empty($backgroundColor) &&
!empty($borderColor) &&
!empty($textColor)
)
{
$code = 200;
$message = '';
if(empty($calendarId))
{
$calendar = new Calendar;
$code = 201;
}
else
{
$calendar = $calendarRepository->find($calendarId);
}
$calendar->setTitle($title);
$calendar->setDescription($description);
$calendar->setStart(new DateTime($start));
if($allDay)
{
$calendar->setEnd(new DateTime($start));
}
else
{
$calendar->setEnd(new DateTime($end));
}
$calendar->setAllDay($allDay);
$calendar->setBackgroundColor($backgroundColor);
$calendar->setBorderColor($borderColor);
$calendar->setTextColor($textColor);
$manager->persist($calendar);
$manager->flush();
$message = 'OK';
}
else
{
//return new Response('Incomplete data', 404);
$code = 404;
$message = 'Incomplete data';
}
return new Response($message, $code);
}
I don't understand where #ParamConverter is used.
Related
Hi I have a problem with getting the value of input using request in Controller, it's always return null. This is my code in jquery I am using Ajax to pass value to controller.
$('.generate').click(function(){
var dstart = $("#datepickerstart").val();
var dend = $("#datepickerend").val();
//var empid = $('#empid').val();
if($('#empid').val().length == 0)
{
empid = 0;
}
else{
empid = $('#empid').val();
}
var dStart = 0;
var dEnd = 0;
//alert(empid);
$.ajax({
type: "GET",
url: "{{route('manageattendance', '')}}"+"/"+empid,
data:$('#attendanceform').serialize(),
success: function(response)
{
console.log(response);
// alert("data caught");
$('.content').load('manageattendance/'+empid);
},
error: function(error)
{
console.log(error);
//alert("not caught ");
// alert($('#editForm').serialize());
}
});
//alert(dstart);
//alert(dend);
});
And this is my code in controller. I am trying to get the data using request but it returns null when I checked it. What would be the cause? Please help me. Thanks
public function index($id = 0,Request $request)
{
if($id == 0){
$current_date = date('Y-m-d');
$attendances = Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')-
>where('Date','=',$current_date)->get();
//$start = '2021-02-10';
//$end = '2021-02-11';
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances'));
}
else
{
$start = $request->input('datepickerstart');
$end = $request->input('datepickerend');
$newS = date('Y-m-d', strtotime($start));
$newE = date('Y-m-d', strtotime($end));
$sUser = User::select('name')->where('id','=',$id)->get();
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->where('user_id','=',$id)-
>get();
$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances','sUser'));
// dd($start);
}
// return view('manage.index');
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
}
don't forget {{csrf_field }} in form and put id in input name is id
$('.generate').click(function(){
var dstart = $("#datepickerstart").val();
var dend = $("#datepickerend").val();
//var empid = $('#empid').val();
if($('#empid').val().length == 0)
{
empid = 0;
}
else{
empid = $('#empid').val();
}
var dStart = 0;
var dEnd = 0;
//alert(empid);
$.ajax({
type: "GET",
url: "{{route('manageattendance.update')}}"+"/"+empid,
data:$('#attendanceform').serialize(),
success: function(response)
{
console.log(response);
// alert("data caught");
$('.content').load('manageattendance/'+empid);
},
error: function(error)
{
console.log(error);
//alert("not caught ");
// alert($('#editForm').serialize());
}
});
//alert(dstart);
//alert(dend);
});
public function index(Request $request)
{
if(request->id == 0){
$current_date = date('Y-m-d');
$attendances = Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')-
>where('Date','=',$current_date)->get();
//$start = '2021-02-10';
//$end = '2021-02-11';
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances'));
}
else
{
$start = $request->input('datepickerstart');
$end = $request->input('datepickerend');
$newS = date('Y-m-d', strtotime($start));
$newE = date('Y-m-d', strtotime($end));
$sUser = User::select('name')->where('id','=',$request->id)->get();
$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->where('user_id','=',$request->id)->whereBetween('Date',
[$start,$end])-
>get();
return view('manage.index',compact(['attendances'=>$attendances,'sUser'=>$sUser]));
// dd($start);
}
}
Im in trouble with this code, I cant store my dataP array objects into mysql.
Ajax request :
$.ajax({
url:'/register/addpostulantR',
method:'post',
dataType: "text",
data:JSON.stringify(dataP),
success(data){
console.log("succ "+data);
},
error:()=>{
console.log('error ');
}
})
Controller:intervenantController.php
public static function addPostulantR(Request $request)
{
return response()->json([
'dataP' => Intervenant::addPostulantR($request->all())
]);
//The dataP is my json
}
Model: Intervenant.php
public static function addPostulantR($data)
{
//$test = json_decode($data);
$id = 0;
foreach($data as $dataP) {
$id = DB::table('reponse')->insertGetId($dataP);
}
return $id;
}
Array: From my javascript
let dataP = [
{
fk_id_quest:1,
fk_id_post:id,
reponse : $("#descriptif_offre").val(),
created_at:date.getTime()/1000,
},
{
fk_id_quest:2,
fk_id_post:id,
reponse : $("#descriptif_offre").val(),
created_at:date.getTime()/1000,
}
];
Thanks a lot..
Controller
Email.PHP
`
public function execute()
{
$customerEmail=$this->getRequest()->getParam('email');
$objectManager=\Magento\Framework\App\ObjectManager::getInstance();
$CustomerModel = $objectManager->create('Magento\Customer\Model\Customer');
$CustomerModel->setWebsiteId(1);
$CustomerModel->loadByEmail($customerEmail);
$userId = $CustomerModel->getId();
if ($userId) {
return 1;
} else {
return 0;
}
}`
j Query
jQuery(function() {
var emailAddress = jQuery('#email_address');
emailAddress.on("change", function () {
var mail=emailAddress.val();
jQuery.ajax({
type: "POST",
url: "/customer/email/",
dataType: "json",
data: {email: mail},
success: function (exist) {
if (exist == 1) {
alert("exist");
} else if (exist == 0) {
alert("exist");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error " + jqXHR.status + " " + jqXHR.statusText);
}
});
});
});
I want to check email before clicking create an account button using Ajax, i am not getting to do that, please help me out to solve this issue, thanks in advance.
It seems like you are trying to validate email address as customer enter his email address. For this you just need minor change in the email address field.
<input type="email" name="email" id="email_address" autocomplete="off" value="<?php echo $block->escapeHtml($block->getFormData()->getEmail()) ?>" title="<?php /* #escapeNotVerified */ echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true, 'remote':'<?php echo $this->getUrl('customcustomer/index/uniqueemail', ['_secure' => true]); ?>'}"/>
Create a controller and add you logic in execute method.
<?php
namespace Gaurav\CustomCustomer\Controller\Index;
use Magento\Framework\App\Action\Action;
class Uniqueemail extends Action
{
/**
* #var \Magento\Framework\Controller\Result\JsonFactory
*/
protected $resultJsonFactory;
/**
* #var \Magento\Customer\Model\Customer
*/
protected $_customerModel;
/**
* #param \Magento\Framework\App\Action\Context $context
* #param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Customer\Model\Customer $customerModel
) {
$this->resultJsonFactory = $resultJsonFactory;
$this->_customerModel = $customerModel;
parent::__construct($context);
}
public function execute()
{
$resultJson = $this->resultJsonFactory->create();
$email = $this->getRequest()->getParam('email');
$customerData = $this->_customerModel->getCollection()
->addFieldToFilter('email', $email);
if(!count($customerData)) {
$resultJson->setData('true');
} else {
$resultJson->setData('That email is already taken, try another one');
}
return $resultJson;
}
}
I hope this will be helpful to you.
Simple call a ajax like this
var mail = 'test#.com';
jQuery.ajax({
type: "POST",
url: "/module/checkemail/",
dataType: "json",
data: {email: mail},
success: function (exist) {
if (exist == 1) {
// js for email exists
} else if (exist == 0) {
// js for not
}
},
error: function (jqXHR, textStatus, errorThrown) {
// error handling
}
});
Than make a controller and load customer by email
$CustomerModel = $objectManager->create('Magento\Customer\Model\Customer');
$CustomerModel->setWebsiteId(1); **//Here 1 means Store ID**
$CustomerModel->loadByEmail($customerEmail);
$userId = $CustomerModel->getId();
if ($userId) {
return 1;
} else {
return 0;
}
i
if you get true than email exists.
Hi I am able to retrieve data from a specific table using codeigniter ajax but i don't see everything.
It's simply a chat system I implemented allowing users to send messages to one another.
Everytime a new record is inserted, the latest record does not show up but the previous ones do.
Please see my code attached with this.
Thank you.
Controller - Chats.php
public function ajax_get_chat_messages()
{
echo $this->_get_chat_messages();
}
public function _get_chat_messages()
{
$recipient = $this->input->post('recipient');
$chat = $this->Chats_model->get_chat_messages($recipient);
if($chat->num_rows() > 0)
{
$c_html = '<ul>';
foreach($chat->result() as $cht)
{
$c_html .= '<li>'.$cht->username.'</li>';
$c_html .= '<p>'.$cht->chat_message_content.'</p><hr><br>';
}
$c_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $c_html);
return json_encode($result);
}
}
JS - Chat2.js
$(document).ready(function () {
setInterval(function () { get_chat_messages();}, 2500)
function get_chat_messages()
{
$.post(base_url + "user/chats/ajax_get_chat_messages", {recipient: recipient}, function (data) {
if (data.status == 'ok')
{
$("div#view").html(data.content);
} else
{
//there was an error do something
}
}, "json");
}
/*function get_chat_messages() {
$.ajax({
type: "POST",
dataType: 'json',
url: base_url +"user/chats/ajax_get_chat_messages",
data: {recipient: recipient}, // pass it as POST parameter
success: function(data){
$("div#view").html(data);
console.log(data);
}
});
} */
get_chat_messages();
});
model - Chats_model.php
public function get_chat_messages($recipient)
{
$session = $this->session->userdata('user_id');
$query = "SELECT * FROM chat_messages cm JOIN users u on u.user_id = cm.user_id where cm.user_id = $session and cm.recipient = $recipient or cm.user_id = $recipient and cm.recipient = $session ORDER BY cm.chat_message_id ASC ";
$result = $this->db->query($query, array($recipient));
return $result;
}
Image also attached
Hallo i have problems with my FullCalendar app in Symfony2.
Im not sure but i think an error in my route.
This is my code in the FullCalendar.
$.ajax({
url: '{{ path('pspiess_letsplay_booking_add') }}',
data: {"title": title, "start": start, "end": end},
type: 'post',
success: function(result) {
alert('OK');
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
})
This is my route
pspiess_letsplay_booking_add:
pattern: /admin/booking/add
defaults: { _controller: pspiessLetsplayBundle:Booking:add }
This is my controller
/**
* Lists all Booking entities for Calendar.
*
* #Route("/", name="booking_add")
* #Method("GET")
* #Template()
*/
public function addReservation() {
$em = $this->getDoctrine()->getManager();
$serializer = SerializerBuilder::create()->build();
$qb = $em->createQueryBuilder();
$qb->select('b')
->from('pspiessLetsplayBundle:Booking', 'b');
$query = $qb->getQuery();
$jsonContent = $query->getResult();
$rows = array();
foreach ($jsonContent as $obj) {
$rows[] = array(
'title' => "test",
'start' => $obj->getStart()->format('Y-m-d H:i:s'),
'end' => $obj->getEnd()->format('Y-m-d H:i:s'),
'className' => 'label-success',
);
}
$jsonContent = $serializer->serialize($rows, 'json');
return array(
'entities' => $jsonContent,
);
}
Is there some tutorials how to use the FullCalendar with Symfony2? I searched the whole web, but i dont found anything...
There are some Problems in my code. Here is a sample, it works fine for me.
My controller action
public function addReservationAction() {
$em = $this->getDoctrine()->getManager();
//fetch the POST Data
$request = $this->get('request');
$data = $request->request->all();
//save the Reservation
$booking = new Booking();
$booking->setTitle($data["title"]);
$booking->setStart(new \DateTime($data["start"]));
$booking->setEnd(new \DateTime($data["end"]));
$em->persist($booking);
$em->flush();
//return response
$serializedEntity = $this->container->get('serializer')->serialize($booking, 'json');
$response = new Response($serializedEntity);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
My Route
pspiess_letsplay_booking_add:
pattern: /admin/booking/add
defaults: { _controller: pspiessLetsplayBundle:Booking:addReservation }
My Script code
$.ajax({
url: '{{ path('pspiess_letsplay_booking_add') }}',
data: {"title": title, "start": start, "end": end},
type: 'post',
success: function(result) {
$('#calendar1').fullCalendar('renderEvent', {
title: title,
start: start,
end: end,
}, true);
$(".title").val(""); // clear title field
},
error: function(jqXHR, exception) {
},
})