本文整理汇总了PHP中Symfony\Component\HttpFoundation\JsonResponse::setData方法的典型用法代码示例。如果您正苦于以下问题:PHP JsonResponse::setData方法的具体用法?PHP JsonResponse::setData怎么用?PHP JsonResponse::setData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\HttpFoundation\JsonResponse
的用法示例。
在下文中一共展示了JsonResponse::setData方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getSlugAction
/**
* Get the slug of a string in AJAX
*
* @param $request The request. String to slug must be sent in $request['toSlug']
*
* @return $response Response
*/
public function getSlugAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
if ($toSlug = $request->get('toSlug')) {
$slug = $this->container->get('lch.seo.tools')->getSlug($toSlug);
$em = $this->getDoctrine()->getManager();
$currentSite = $request->getSession()->get('currentSite');
if (class_exists('\\LCH\\CatalogBundle\\Entity\\' . $request->get('className'))) {
$entitySlug = $em->getRepository('LCHCatalogBundle:' . $request->get('className'))->findOneBySlug($slug);
} elseif (class_exists('\\LCH\\ModuleBundle\\Entity\\' . $request->get('className'))) {
$entitySlug = $em->getRepository('LCHModuleBundle:' . $request->get('className'))->findOneBySlug($slug);
} else {
throw new NotFoundHttpException("Class " . $request->get('className') . " no exists");
}
// if slug already exists
$response = new JsonResponse();
$id = $request->get('id') != "" ? $request->get('id') : "0";
$url = $this->container->get('lch.seo.tools')->getFrontUrlRedirection($id, $slug, $request->get('className'));
if ($entitySlug) {
if ($request->get('id') == $entitySlug->getId()) {
// If the slug comes from the same entity
$response->setData(array('slug' => $slug, 'message' => $this->container->get('translator')->trans('seo.form.url.infos') . " " . $url));
} else {
$response->setData(array('slug' => $slug, 'error' => $this->container->get('translator')->trans("app.slugexists")));
}
} else {
$response->setData(array('slug' => $slug, 'message' => $this->container->get('translator')->trans('seo.form.url.infos') . " " . $url));
}
return $response;
}
}
}
示例2: onKernelException
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$response = new JsonResponse(['errorMessage' => $event->getException()->getMessage(), 'stackTrace' => $event->getException()->getTraceAsString()]);
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
} else {
if ($exception instanceof AuthenticationException) {
$response->setData(['errorMessage' => 'You don\'t have permissions to do this.']);
$response->setStatusCode(Response::HTTP_FORBIDDEN);
} else {
if ($exception instanceof InvalidFormException) {
$errors = [];
foreach ($exception->getForm()->getErrors(true) as $error) {
if ($error->getOrigin()) {
$errors[$error->getOrigin()->getName()][] = $error->getMessage();
}
}
$data = ['errors' => $errors, 'errorMessage' => ''];
$response->setData($data);
$response->setStatusCode(Response::HTTP_BAD_REQUEST);
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
}
$event->setResponse($response);
}
示例3: saveAction
/**
* Process Ajax Form to create/update virtual product
*
* @param int $idProduct
* @param Request $request
*
* @return string
*/
public function saveAction($idProduct, Request $request)
{
$response = new JsonResponse();
$legacyContext = $this->container->get('prestashop.adapter.legacy.context');
$adminProductWrapper = $this->container->get('prestashop.adapter.admin.wrapper.product');
$productAdapter = $this->container->get('prestashop.adapter.data_provider.product');
//get product
$product = $productAdapter->getProduct((int) $idProduct, true);
if (!$product || !$request->isXmlHttpRequest()) {
return $response;
}
$form = $this->createForm('PrestaShopBundle\\Form\\Admin\\Product\\ProductVirtual', null, array('csrf_protection' => false));
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
$res = $adminProductWrapper->updateDownloadProduct($product, $data);
$res->file_download_link = $res->filename ? $legacyContext->getAdminBaseUrl() . $res->getTextLink(true) : '';
$product->is_virtual = 1;
$product->save();
$response->setData($res);
} else {
$response->setStatusCode(400);
$response->setData($this->getFormErrorsForJS($form));
}
return $response;
}
示例4: onKernelException
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$response = new JsonResponse();
$detail = sprintf("Message: %s\nFile: %s:%s", $exception->getMessage(), $exception->getFile(), $exception->getLine());
$data = ['type' => '#0', 'code' => 0, 'title' => 'Internal Server Error', 'status' => JsonResponse::HTTP_INTERNAL_SERVER_ERROR, 'detail' => $detail];
$response->setStatusCode(JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
$response->setData($data);
if ($exception instanceof HttpExceptionInterface) {
$response->headers->replace($exception->getHeaders());
}
if ($exception instanceof HttpException) {
$data = ['type' => '#' . $exception->getCode(), 'code' => $exception->getCode(), 'title' => $exception->getMessage(), 'status' => JsonResponse::HTTP_BAD_REQUEST, 'detail' => $exception->getDetails()];
$response->setStatusCode(JsonResponse::HTTP_BAD_REQUEST);
$response->setData($data);
}
if ($exception instanceof AccessDeniedHttpException) {
$event->setResponse(new Response("", 403));
} else {
$event->setResponse($response);
}
if (!in_array($this->kernel->getEnvironment(), array('dev', 'test'))) {
unset($data['detail']);
}
}
示例5: onKernelException
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$response = new JsonResponse();
$response->setData(['message' => $exception->getMessage()]);
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
}
if ('RuntimeException' === get_class($exception)) {
$response->setStatusCode($exception->getCode());
}
if ($exception instanceof ArrayErrorsException) {
$response->setData(['formErrors' => $exception->getErrors()]);
}
if ($exception instanceof AuthenticationException) {
$response->setData(['message' => $exception->getMessageKey()]);
$response->setStatusCode(JsonResponse::HTTP_BAD_REQUEST);
}
if ($exception instanceof InsufficientAuthenticationException) {
$response->setData(['message' => $this->translator->trans('error.insufficient_authentication')]);
$response->setStatusCode(JsonResponse::HTTP_FORBIDDEN);
}
$event->setResponse($response);
}
示例6: 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;
}
示例7: refresh
/**
* Controller to return the access token when a refresh token is provided.
*
* @todo: Get some flood protection for this, since the request is uncacheable
* because of the expire counter. Also, there has to be some other better way
* to render JSON. Investigate that too!
*/
public function refresh()
{
$account = $this->currentUser()->getAccount();
// If the account is not a token account, then bail.
if (!$account instanceof TokenAuthUserInterface) {
// TODO: Set the error headers appropriately.
return NULL;
}
$refresh_token = $account->getToken();
if (!$refresh_token || !$refresh_token->isRefreshToken()) {
// TODO: Set the error headers appropriately.
return NULL;
}
// Find / generate the access token for this refresh token.
$access_token = $refresh_token->get('access_token_id')->entity;
if (!$access_token || $access_token->get('expire')->value < REQUEST_TIME) {
// If there is no token to be found, refresh it by generating a new one.
$values = ['expire' => $refresh_token::defaultExpiration(), 'user_id' => $refresh_token->get('user_id')->target_id, 'auth_user_id' => $refresh_token->get('auth_user_id')->target_id, 'resource' => $access_token ? $access_token->get('resource')->target_id : 'global', 'created' => REQUEST_TIME, 'changed' => REQUEST_TIME];
/* @var AccessTokenInterface $access_token */
$access_token = $this->entityManager()->getStorage('access_token')->create($values);
// This refresh token is no longer needed.
$refresh_token->delete();
// Saving this token will generate a refresh token for that one.
$access_token->save();
}
$this->response->setData($this->normalize($access_token));
return $this->response;
}
示例8: addAction
/**
* Manage form add product attachment
*
* @param int $idProduct
* @param Request $request
*
* @return string
*/
public function addAction($idProduct, Request $request)
{
$response = new JsonResponse();
$legacyContext = $this->container->get('prestashop.adapter.legacy.context');
$adminProductWrapper = $this->container->get('prestashop.adapter.admin.wrapper.product');
$productAdapter = $this->container->get('prestashop.adapter.data_provider.product');
//get product
$product = $productAdapter->getProduct((int) $idProduct);
if (!$product || !$request->isXmlHttpRequest()) {
return $response;
}
$form = $this->createForm('PrestaShopBundle\\Form\\Admin\\Product\\ProductAttachement', null, array('csrf_protection' => false));
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
$res = $adminProductWrapper->processAddAttachment($product, $data, $legacyContext->getLanguages());
if ($res) {
$res->real_name = $data['name'];
$response->setData($res);
}
} else {
$response->setStatusCode(400);
$response->setData($this->getFormErrorsForJS($form));
}
return $response;
}
示例9: sendEmailAction
/**
* Request reset user password: submit form and send email
*/
public function sendEmailAction(Request $request)
{
$username = $request->get('username');
$template = $request->get('template');
$routereset = $request->get('routereset');
$type = $request->get('type');
if (empty($template)) {
$template = str_replace('::', ':', $this->container->getParameter('sfynx.auth.theme.login')) . 'Resetting:request.html.twig';
}
$user = $this->container->get('doctrine')->getManager()->getRepository('SfynxAuthBundle:User')->findOneBy(array('username' => $username));
if ($request->isXmlHttpRequest()) {
$response = new JsonResponse();
if (null === $user) {
return $response->setData(json_encode(array('text' => 'Identifiant inconnu', 'error' => true, 'type' => 'unknown')));
} else {
if ($user->isPasswordRequestNonExpired($this->container->getParameter('fos_user.resetting.token_ttl')) && $type == 'send') {
return $response->setData(json_encode(array('text' => 'Vous devez au préalable activer votre compte en cliquant sur le mail de Confirmation d\'inscription reçu', 'error' => true, 'type' => '24h')));
} else {
$tokenGenerator = $this->container->get('fos_user.util.token_generator');
$user->setConfirmationToken($tokenGenerator->generateToken());
$em = $this->container->get('doctrine')->getManager();
$em->persist($user);
$em->flush();
$this->container->get('session')->set(PiMailerManager::SESSION_EMAIL, $this->container->get('sfynx.auth.mailer')->getObfuscatedEmail($user));
$this->container->get('sfynx.auth.mailer')->sendResettingEmailMessage($user, $routereset);
$user->setPasswordRequestedAt(new \DateTime());
$this->container->get('fos_user.user_manager')->updateUser($user);
return $response->setData(json_encode(array('text' => 'Un email vous a été envoyé pour créer un nouveau mot de passe sur le site', 'error' => false)));
}
}
} else {
if (null === $user) {
return $this->container->get('templating')->renderResponse($template, array('invalid_username' => $username));
}
if ($user->isPasswordRequestNonExpired($this->container->getParameter('fos_user.resetting.token_ttl'))) {
return $this->container->get('templating')->renderResponse(str_replace('::', ':', $this->container->getParameter('sfynx.auth.theme.login')) . 'Resetting:passwordAlreadyRequested.html.twig');
}
$tokenGenerator = $this->container->get('fos_user.util.token_generator');
$user->setConfirmationToken($tokenGenerator->generateToken());
$em = $this->container->get('doctrine')->getManager();
$em->persist($user);
$em->flush();
//
$this->container->get('session')->set(PiMailerManager::SESSION_EMAIL, $this->container->get('sfynx.auth.mailer')->getObfuscatedEmail($user));
$this->container->get('sfynx.auth.mailer')->sendResettingEmailMessage($user, $routereset);
$user->setPasswordRequestedAt(new \DateTime());
$this->container->get('fos_user.user_manager')->updateUser($user);
try {
return $this->container->get('templating')->renderResponse($template, array('success' => true));
} catch (\Exception $e) {
$response = new RedirectResponse($this->container->get('router')->generate('fos_user_resetting_check_email'));
}
return $response->getContent();
}
}
示例10: expiredAction
public function expiredAction($id)
{
$utilis = $this->getDoctrine()->getRepository('GenericBundle:User')->find($id);
$reponse = new JsonResponse();
if ($utilis->isExpired()) {
$utilis->setExpired(false);
$reponse->setData(array('succes' => '0'));
} else {
$utilis->setExpired(true);
$reponse->setData(array('succes' => '1'));
}
$this->getDoctrine()->getEntityManager()->flush();
return $reponse;
}
示例11: onKernelException
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$response = new JsonResponse();
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
$response->setData(array('message' => $exception->getMessage()));
} else {
$response->setData(array('message' => 'An internal server error occurred. Sorry for the inconvenience.'));
$response->setStatusCode(JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
}
$event->setResponse($response);
}
示例12: transform
/**
* @param \Dafiti\Silex\Response $controllerResponse
*
* @return HttpFoundation\Response
*/
protected function transform(\Dafiti\Silex\Response $controllerResponse)
{
$response = new HttpFoundation\JsonResponse();
$response->headers->add(['Content-Type' => self::CONTENT_TYPE]);
$response->setStatusCode($controllerResponse->getStatusCode());
if ($this->hasError()) {
$content = ['message' => $controllerResponse->getErrorMessage()];
$response->setData($content);
return $response;
}
$response->setStatusCode($controllerResponse->getStatusCode());
$content = $this->getContent($controllerResponse);
$response->setData($content);
return $response;
}
示例13: edit
function edit(City $city)
{
$response = new JsonResponse();
$id = $city->getId();
$object = $this->repository->getOneById($id);
if ($object == null) {
$response->setData(array('flag' => false, 'info' => "Error! No object for given id"));
return $response;
}
$object->setName($city->getName());
$object->setPtt($city->getPtt());
$this->repository->flush();
$response->setData(array('flag' => true, 'info' => "ok"));
return $response;
}
示例14: asyncDBCheck
/**
* @Route("/check-connection", name="check-db-connection")
*/
public function asyncDBCheck(Request $request)
{
if ($request->isXMLHttpRequest()) {
$databaseArgs = array('name' => $request->request->get('name'));
$connectionStatus = $this->checkConnection($databaseArgs);
$response = new JsonResponse();
if ($connectionStatus) {
$response->setData(array('action' => 'db_check', 'status' => 'success'));
} else {
$response->setData(array('action' => 'db_check', 'status' => 'failure'));
}
return $response;
}
return new Response('This is not ajax!', 400);
}
示例15: deleteCommentAction
/**
* Deletes a Comment entity.
*
* @Route("/comment/{id}", name="front_comment_delete")
* @Method("DELETE")
* @param Request $request
* @param Comment $comment
* @return JsonResponse
*/
public function deleteCommentAction(Request $request, Comment $comment)
{
$response = new JsonResponse();
// check for "edit" access: calls all voters
$perm = $this->isGranted('edit', $comment);
if ($perm) {
$em = $this->getDoctrine()->getManager();
$em->remove($comment);
$em->flush();
$response->setData(['success' => true]);
} else {
$response->setData(['success' => false]);
}
return $response;
}