本文整理汇总了PHP中Symfony\Component\HttpFoundation\JsonResponse类的典型用法代码示例。如果您正苦于以下问题:PHP JsonResponse类的具体用法?PHP JsonResponse怎么用?PHP JsonResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JsonResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getTimetable
/**
* @Route("/xhr/getTimetable/{id}")
* @Template("canoUEKCBundle:Autocomplete:index.html.twig")
*/
public function getTimetable($id)
{
// $q1 = $this->getDoctrine()->getRepository('canoUEKCBundle:GroupEnt')->createQueryBuilder('groupEnt')
// ->select('groupEnt.name')
// ->where('groupEnt.id = :id')
// ->setParameter('id', $id)
// ->getQuery()->getResult();
$q = $this->getDoctrine()->getRepository('canoUEKCBundle:GroupEnt')->createQueryBuilder('groupEnt')->select('groupEnt, classes')->leftJoin('groupEnt.classes', 'classes')->where('groupEnt.id = :subCompanyId')->setParameter("subCompanyId", $id)->getQuery()->getResult();
$classes = $q[0]->getClasses();
$data = [];
$em = $this->getDoctrine()->getManager();
// ld($classes[0]->getId());
// die();
// $crawlStatus = $em->getRepository('canoUEKCBundle:Classroom')->find($classes[0]->getClassroomId());
for ($i = 0; $i < count($classes); $i++) {
$q = $this->getDoctrine()->getRepository('canoUEKCBundle:Teacher')->createQueryBuilder('teacher')->select('teacher.name', 'teacher.lastname')->leftJoin('teacher.classes', 'classes')->where('classes.id = :query')->setParameter('query', $classes[$i]->getId())->getQuery()->getResult();
// ld($q[0]['name']);
// ;die();
$data[$i]['YYYY'] = $classes[$i]->getDate()->format("Y");
$data[$i]['MM'] = $classes[$i]->getDate()->format("m");
$data[$i]['DD'] = $classes[$i]->getDate()->format("d");
$data[$i]['startTime'] = $classes[$i]->getStartTime()->format("H:i");
$data[$i]['endTime'] = $classes[$i]->getEndTime()->format("H:i");
$data[$i]['classroom'] = $em->getRepository('canoUEKCBundle:Classroom')->find($classes[0]->getClassroomId())->getName();
$data[$i]['type'] = $em->getRepository('canoUEKCBundle:ClassType')->find($classes[0]->getTypes())->getName();
$data[$i]['teacher'] = $q[0]['name'] . ' ' . $q[0]['lastname'];
}
$response = new JsonResponse();
$response->setData($data);
return $response;
}
示例2: statisticsJsonAction
/**
*
* @Route("/{_locale}/{_code}/statistics/{dataset}.json", requirements={"_locale" = "de|en|es|fr", "_code" = "[a-zA-Z0-9]{10}", "dataset" = "[a-zA-Z0-9_-]+"})
*/
public function statisticsJsonAction($_code, $dataset, Request $request)
{
try {
$context = $this->getContext($_code, 'statistics');
$stats = new Statistics($this, $this->account);
if (preg_match('!^wallet-([0-9]+)$!', $dataset, $m)) {
$method = 'getDatasetWallet';
if (method_exists($stats, $method)) {
$data = $stats->{$method}($m[1]);
if (!empty($data)) {
$response = new JsonResponse($data);
}
}
} else {
$method = 'getDataset' . $dataset;
if (method_exists($stats, $method)) {
$response = new JsonResponse($stats->{$method}());
}
}
if (isset($response)) {
$response->setMaxAge(900);
$response->setExpires(new \DateTime('@' . (time() + 900)));
$response->setPublic();
return $response;
}
} catch (\Exception $ex) {
return new JsonResponse(['error' => $ex->getMessage()]);
}
}
示例3: onKernelException
/**
* @param GetResponseForExceptionEvent $event
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$code = $exception->getCode();
$debug = array('class' => get_class($exception), 'code' => $code, 'message' => $exception->getMessage());
$this->logger->error(print_r($debug, true));
// HttpExceptionInterface est un type d'exception spécial qui
// contient le code statut et les détails de l'entête
if ($exception instanceof NotFoundHttpException) {
$data = array('error' => array('code' => $code ? $code : -3, 'message' => $exception->getMessage()));
$response = new JsonResponse($data);
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
$response->headers->set('Content-Type', 'application/json');
} elseif ($exception instanceof HttpExceptionInterface) {
$data = array('error' => array('code' => $code ? $code : -2, 'message' => $exception->getMessage()));
$response = new JsonResponse($data);
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
$response->headers->set('Content-Type', 'application/json');
} else {
$data = array('error' => array('code' => $code ? $code : -1, 'message' => 'Internal Server Error / ' . $exception->getMessage()));
$response = new JsonResponse($data);
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
// envoie notre objet réponse modifié à l'évènement
$event->setResponse($response);
}
示例4: RefreshNotificationAction
public function RefreshNotificationAction($id, Request $request)
{
if ($request->isXmlHttpRequest()) {
// si on appele depuis une requette ajax
$em = $this->getDoctrine()->getManager();
$Allnotifs = $em->getRepository('OCNotificationBundle:Notification')->findByPourAgent($id);
if ($Allnotifs) {
$notifs = array();
foreach ($Allnotifs as $notif) {
$interval = $notif->getDateCreation()->diff(new \DateTime('now'));
if ($interval->format('%a') == "0") {
$date = "aujourd'hui";
} elseif ($interval->format('%a') == "1") {
$date = "hier";
} else {
$date = $interval->format('%a jours');
}
if ($notif->getEventAssocie() !== null) {
$nom_agent = $notif->getEventAssocie()->getAgent()->getNomCanonique();
} else {
$nom_agent = $notif->getHSFAssocie()->getAgent()->getNomCanonique();
}
$notifs[$notif->getId()] = array($notif->getId(), $nom_agent, $notif->getTitle(), $notif->getVisionee(), $date);
}
} else {
$notif = null;
}
//var_dump($notifs);
//die();
$response = new JsonResponse();
return $response->setData(array('notifs' => $notifs));
} else {
throw new Exception("Vous n'etes pas censés être ici ! Cassez vous !");
}
}
示例5: JsonData
/**
* @Route("/admin/testimonials/jsondata", name="admin_testimonials_jsondata")
*/
public function JsonData(Request $request)
{
$sortColumn = $request->get('sidx');
$sortDirection = $request->get('sord');
$pageSize = $request->get('rows');
$page = $request->get('page');
$callback = $request->get('callback');
$repo = $this->getDoctrineRepo('AppBundle:Testimonial');
$dataRows = $repo->getGridOverview($sortColumn, $sortDirection, $pageSize, $page);
$rowsCount = $repo->countAll();
$pagesCount = ceil($rowsCount / $pageSize);
$rows = array();
// rows as json result
foreach ($dataRows as $dataRow) {
// build single row
$row = array();
$row['id'] = $dataRow->getId();
$cell = array();
$i = 0;
$cell[$i++] = '';
$cell[$i++] = $dataRow->getId();
$cell[$i++] = $dataRow->getName();
$cell[$i++] = $dataRow->getAge();
$cell[$i++] = $dataRow->getPlace();
$cell[$i++] = $dataRow->getPosition();
$row['cell'] = $cell;
array_push($rows, $row);
}
$result = array('records' => $rowsCount, 'page' => $page, 'total' => $pagesCount, 'rows' => $rows);
$resp = new JsonResponse($result, JsonResponse::HTTP_OK);
$resp->setCallback($callback);
return $resp;
}
示例6: updateAction
/**
* @Secure(roles="ROLE_USER, ROLE_ADMINISTRATOR")
*/
public function updateAction(Request $request)
{
$params = [];
$requestBody = $this->get("request")->getContent();
if (!empty($requestBody)) {
$params = json_decode($requestBody, true);
$em = $this->getDoctrine()->getManager();
$user = $this->get('security.context')->getToken()->getUser();
//$slices = explode(':', $params['grid']);
//array_pop($slices);
$grid = $params['grid'];
$fields = implode('|', $params['fields']);
//$layout = $this->get('app_core.grid_layout_repository')
$layout = $em->getRepository('CoreBundle:GridLayout')->findUserLayout($grid, $user->getId());
if (is_null($layout)) {
$layout = new GridLayout();
}
$layout->setUser($user);
$layout->setGrid($grid);
$layout->setLayout($fields);
$em->persist($layout);
$em->flush();
}
$response = new JsonResponse();
$responseBody = [];
$response->setData($responseBody);
return $response;
}
示例7: addSimpleCategoryFormAction
/**
* Process Ajax Form to add a simple category (name and parent category)
*
* @param Request $request
*
* @return string
*/
public function addSimpleCategoryFormAction(Request $request)
{
$response = new JsonResponse();
$tools = $this->container->get('prestashop.adapter.tools');
$shopContext = $this->container->get('prestashop.adapter.shop.context');
$shopList = $shopContext->getShops(false, true);
$currentIdShop = $shopContext->getContextShopID();
$form = $this->createFormBuilder()->add('category', 'PrestaShopBundle\\Form\\Admin\\Category\\SimpleCategory')->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
$_POST = ['submitAddcategory' => 1, 'name_1' => $data['category']['name'], 'id_parent' => $data['category']['id_parent'], 'link_rewrite_1' => $tools->link_rewrite($data['category']['name']), 'active' => 1, 'checkBoxShopAsso_category' => $currentIdShop ? [$currentIdShop => $currentIdShop] : $shopList];
$adminCategoryController = $this->container->get('prestashop.adapter.admin.controller.category')->getInstance();
if ($category = $adminCategoryController->processAdd()) {
$response->setData(['category' => $category]);
}
if ($request->query->has('id_product')) {
$productAdapter = $this->get('prestashop.adapter.data_provider.product');
$product = $productAdapter->getProduct($request->query->get('id_product'));
$product->addToCategories($category->id);
$product->save();
}
} else {
$response->setStatusCode(400);
$response->setData($this->getFormErrorsForJS($form));
}
return $response;
}
示例8: dbAction
public function dbAction(Db $db, JsonResponse $response)
{
$conn = $db->getConnection();
$sql = "SELECT * FROM test";
$stmt = $conn->query($sql);
return $response->setData($stmt->fetchAll());
}
示例9: start
/**
* @inheritdoc
*/
public function start(Request $request, AuthenticationException $authException = null)
{
$response = new JsonResponse();
$response->setStatusCode(401);
$response->setData(['ok' => false, 'error' => 'Accessing this resource requires authorization']);
return $response;
}
示例10: findReceiverAction
public function findReceiverAction()
{
$em = $this->getDoctrine()->getManager();
$name_receiver = $em->getRepository('DBdbBundle:User')->findAllUserByName();
$response = new JsonResponse();
return $response->setData(array('name_receiver' => $name_receiver));
}
示例11: updateAction
public function updateAction()
{
$em = $this->getDoctrine()->getManager();
$repoLignesCmd = $em->getRepository("Gestion\\ArticlesBundle\\Entity\\LignesCommande");
$designation = $this->get('request')->request->get('designation');
// ok
$prixTTC = $this->get('request')->request->get('prixTTC');
// ok
$detail = $this->get('request')->request->get('detail');
// ok
$idLigneCmd = $this->get('request')->request->get('idLgnCmd');
// ok
$LigneCmd = $repoLignesCmd->findOneById($idLigneCmd);
if (isset($designation)) {
$LigneCmd->setDesignation($designation);
} elseif (isset($prixTTC)) {
$newHT = $prixTTC / ($LigneCmd->getTva() / 100 + 1);
$LigneCmd->setPrixHt($newHT);
} elseif (isset($detail)) {
$LigneCmd->setDetail($detail);
}
$em->persist($LigneCmd);
$em->flush();
$response = new JsonResponse();
return $response->setData(array('designation' => $designation, 'designation 2' => $LigneCmd->getDesignation(), 'prixTTC' => $prixTTC, 'idLgnCmd' => $idLigneCmd, 'detail' => $detail));
}
示例12: buildErrorMessage
/**
* Building error message
*
* @param string $message
*/
private function buildErrorMessage($message)
{
$response = new JsonResponse();
$response->setData(['error' => $message]);
$response->send();
die;
}
示例13: postMessage
/**
* @Route("/chat-api/message")
*/
public function postMessage(Request $request)
{
$message = new ChatMessage();
$message->setUsername($request->get('username'))->setText($request->get('chat_text'))->setTimestamp(new \DateTime());
$em = $this->getDoctrine()->getManager();
$em->persist($message);
$em->flush();
// Uncomment this to publish to redis and use Ratchet or Faye
// $data = [
// 'event' => 'new-message',
// 'data' => $message
// ];
// $jsonContent = json_encode($data);
// $redis = new Client('tcp://127.0.0.1:6379');
// $redis->publish('chat', $jsonContent);
// Uncomment this to use Pusher
// $pusher = $this->container->get('lopi_pusher.pusher');
// $pusher->trigger(
// 'chat',
// 'new-message',
// $message
// );
$response = new JsonResponse();
$response->setData($message);
return $response;
}
示例14: retrieveEvent
/**
* @Route("/evento/get", name="get_event")
*/
public function retrieveEvent()
{
$request = Request::createFromGlobals();
$from = $request->query->get('from');
$to = $request->query->get('to');
if ($from && $to) {
$em = $this->getDoctrine()->getManager();
$q = "SELECT e FROM AppBundle\\Entity\\Evento e WHERE (e.fechainicio>=:from AND e.fechainicio<=:to) OR (e.fechafin>=:from AND e.fechafin<=:to)";
$query = $em->createQuery($q);
$query->setParameter('from', date("Y/m/d H:i:s", $from / 1000));
$query->setParameter('to', date("Y/m/d H:i:s", $to / 1000));
$events = $query->getResult();
$jevents = array();
foreach ($events as $ev) {
$jevents[] = array("id" => $ev->getIdEvento(), "title" => $ev->getDescripcion(), "url" => "http://example.com", "class" => "event-important", "start" => 1000 * strtotime($ev->getFechainicio()->format('Y-m-d H:i:s')), "end" => 1000 * strtotime($ev->getFechafin()->format('Y-m-d H:i:s')));
}
$result = array("success" => 1, "result" => $jevents);
$response = new JsonResponse();
$response->setData($result);
return $response;
} else {
$result = array("success" => 1, "result" => array());
$response = new JsonResponse();
$response->setData($result);
return $response;
}
}
示例15: choicesAction
/**
* Search for the specified entity by its property
*
* @Route("/choices/{class}/{property}", name="BluemesaCoreBundle_ajax_choices")
*
* @param Request $request
* @param string $class Entity class to search for
* @param string $property Property to lookup in search
* @return Response
* @throws InvalidArgumentException
*/
public function choicesAction(Request $request, $class, $property)
{
$query = $request->query->get('query');
$repository = $this->getDoctrine()->getRepository($class);
if (!$repository instanceof EntityRepository) {
throw new InvalidArgumentException();
}
$qb = $repository->createQueryBuilder('b');
$terms = explode(" ", $query);
foreach ($terms as $term) {
$qb = $qb->andWhere("b." . $property . " like '%" . $term . "%'");
}
$found = $qb->getQuery()->getResult();
$propertyPath = null !== $property ? new PropertyPath($property) : null;
$propertyAccessor = PropertyAccess::createPropertyAccessor();
$options = array();
foreach ($found as $entity) {
if (null !== $propertyPath) {
$options[] = (string) $propertyAccessor->getValue($entity, $propertyPath);
} else {
$options[] = (string) $entity;
}
}
$response = new JsonResponse();
$response->setData($options);
return $response;
}