API Platform custom operation response - dompdf

I need to return a PDF file using DomPDF, from a custom operation in API Platform, for exporting the entity data. After spending time studying the documentation, and doing many searches on the internet, I came up with a setup, but it still doesn't work.
Here's my entity
namespace App\Entity\ProjectManagement;
...
/**
* Class Ticket
* #package App\Entity\ProjectManagement
* #ApiResource(
* routePrefix="/projmgmt",
* shortName="Ticket",
* normalizationContext={"groups"={"appentity:read", "appgeneratedcodeentity:read", "ticket:read"}},
* denormalizationContext={"groups"={"appentity:write", "appgeneratedcodeentity:write", "ticket:write"}},
* itemOperations={
* "get", "put", "patch", "delete",
* "export"={
* "method"="GET",
* "path"="/tickets/{id}/export",
* "controller"=ExportTicketAction::class,
* "openapi_context"={
* "responses"={
* "200"={
* "content"={
* "application/pdf"={
* "schema"={
* "type"="string",
* "format"="binary",
* }
* }
* }
* }
* }
* }
* }
* }
* )
* #ApiFilter(PropertyFilter::class)
* #UniqueEntity(fields="code", message="The code {{ value }} already exists in the DB.")
* #ORM\Table(name="gestop_projmgmt_ticket")
* #ORM\Entity(repositoryClass=TicketRepository::class)
*/
class Ticket
{
...
and here's my controller
namespace App\Controller\ProjectManagement;
...
/**
* Class ExportTicketAction
* #package App\Controller\ProjectManagement
*/
final class ExportTicketAction extends AppController
{
/**
* #param Ticket $ticket
* #return Response
*/
public function __invoke(Ticket $ticket): Response
{
$dompdf = (new Dompdf((new Options())
->set('defaultFont', 'Arial')
->set('isPhpEnabled', true)
->set('isRemoteEnabled', true)))
->setPaper('A4', 'portrait');
$dompdf->loadHtml($this->renderView('/reports/projmgmt/ticket.html.twig', ['ticket' => $ticket]));
$dompdf->render();
return new Response($dompdf->output(), 200, ['Content-Type' => 'application/pdf']);
}
}
At the moment the Twig template doesn't have much information, I just need it to work and then I start designing it.
{% extends 'report.html.twig' %}
{% block report_title %}{{ 'gestop.entity.projmgmt.ticket'|trans }}{% endblock %}
{% block report_css %}
<style>
body { font-family: Arial, Helvetica, sans-serif; }
header { text-align: center; }
footer { font-size: small; }
</style>
{% endblock %}
{% block report_header %}{{ 'gestop.entity.projmgmt.ticket'|trans }}{% endblock %}
{% block report_content %}
<p>test</p>
{% endblock %}
Please, what am I doing wrong, or am I even on the right track?

Related

button like/dislike with symfony 3

I have in my patient space, a list of doctors with whom he has made an appointment.And next to each doctor, I want to add a button I like so that the patient can tell if he liked or not the consultation with the doctor.
And I would like to know the number of patients who have liked a given doctor. For this number to be displayed in the doctor's details.
Here is my controller where I have my list of doctors
Controller
public function patientBookingListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$medecin = $em->getRepository("DoctixMedecinBundle:Medecin")->findOneBy(array(
'user' => $this->getUser(),
));
$patient = $em->getRepository("DoctixPatientBundle:Patient")->findOneBy(array(
'user' => $this->getUser(),
));
$bookings = $em->getRepository("DoctixFrontBundle:Booking")->findBy(array(
"patient" => $patient
));
$bookings = $this->get('knp_paginator')->paginate($bookings, $request->query->get('page', 1), 3);
return $this->render('DoctixPatientBundle:Patient:bookings.html.twig', array(
'bookings' => $bookings
));
}
I had already create my table favorite_doctor :
Entity favorite_doctor
class MedecinFavoris
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Doctix\PatientBundle\Entity\Patient", inversedBy="medecin_favoris")
* #ORM\JoinColumn(name="patient_id", referencedColumnName="id")
*/
private $patient;
/**
* #ORM\ManyToOne(targetEntity="Doctix\MedecinBundle\Entity\Medecin", inversedBy="medecin_favoris")
* #ORM\JoinColumn(name="medecin_id", referencedColumnName="id")
*/
private $medecin;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set patient
*
* #param \Doctix\PatientBundle\Entity\Patient $patient
*
* #return MedecinFavoris
*/
public function setPatient(\Doctix\PatientBundle\Entity\Patient $patient = null)
{
$this->patient = $patient;
return $this;
}
/**
* Get patient
*
* #return \Doctix\PatientBundle\Entity\Patient
*/
public function getPatient()
{
return $this->patient;
}
/**
* Set medecin
*
* #param \Doctix\MedecinBundle\Entity\Medecin $medecin
*
* #return MedecinFavoris
*/
public function setMedecin(\Doctix\MedecinBundle\Entity\Medecin $medecin = null)
{
$this->medecin = $medecin;
return $this;
}
/**
* Get medecin
*
* #return \Doctix\MedecinBundle\Entity\Medecin
*/
public function getMedecin()
{
return $this->medecin;
}
}
I would like that when I click on the button like that my data is saved in this table.
Twig
{% for booking in bookings %}
<div class="list_general" id="liste">
<ul>
<li>
<figure><img src="{{ vich_uploader_asset(booking.medecin.media, 'imageFile') }}"
alt="{{ booking.medecin.media.imagename }}"></figure>
<h4>Dr. {{ booking.medecin.user.prenom|capitalize }} {{ booking.medecin.user.nom|upper }} <i class="pending">Pending</i></h4>
<ul class="booking_details">
<li><strong>Date et heure</strong>{{ booking.dateHeureRdv|date('d/m/Y') }}</li>
<li><strong>Heure</strong>{{ booking.dateHeureRdv|date('H:i') }}</li>
<li><strong>Motif</strong>Consultation</li>
<li><strong>Téléphone</strong>{{ booking.medecin.user.numTel }}</li>
<li><strong>Email</strong>{{ booking.medecin.user.username }}</li>
</ul>
<ul class="buttons">
<li><i class="fa fa-fw fa-check-circle-o"></i> Déplacer Rdv</li>
<li><i class="fa fa-fw fa-times-circle-o"></i> Annuler</li>
</ul>
</li>
<div class="like">
Like
</div>
</ul>
</div>
{% endfor %}
Now i do not know exactly what to do when i click the like button. Knowing that when a patient like, the data must register in the database and the like button must also disappear to no longer allow him to vote two or more times.
Thanks a lot

Laravel cannot display a selected product details

maybe someone can help me. I have done a product list from my database. It shows product image, title, content, price
When I select on one of the products, it opens in the new window. And I cant see any product details (no image, no title, no content) , just empty page.
See all attachments:
my BrackController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\file;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Collection;
class BracController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('insertBrac');
}
public function showBrac()
{
$user=file::all();
return view('apyrankes', compact('user'));
}
public function view_brac()
{
$object = \DB::table('braclets')->where('BrackID' , request('brackId'))->first();
return view('view_object', array('user' => $object));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
{
$user = new file;
$user->Title= Input::get('title');
$user->Content= Input::get('content');
$user->Price= Input::get('price');
if (Input::hasFile('image'))
{
$file=Input::file('image');
$file->move(public_path(). '/uploads', $file->getClientOriginalName());
$user->Image = $file->getClientOriginalName();
}
$user->save();
return redirect( "insertBrac" );
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
My product list:
apyrankes.blade.php
<div class="header">
#include('header')
</header>
<body>
<div class="content-products">
#foreach($user as $users)
<div id="myDiv">
<div class="products">
<img src="{{ $users->Image}}" alt="{{ $users->Title}}" width="200px" height="200px"><br>
{{ $users->Title}}<br>
{{ $users->Content}}<br>
{{ $users->Price}}€<br>
Plačiau
</div>
</div>
#endforeach
</div>
</body>
And when I select one of the product from product list on apyrankes.blade.php
it opens in view_object.blade.php , but I cannot see there any details of the select product, just empty page:
My view_object.blade.php
<div class="header">
#include('header')
</header>
<body>
<Br>
<br>
<Br>
<div class="content-products">
<div id="myDiv">
<div class="products">
#if($user)
<img src="{{ $user->Image}}" alt="{{ $user->Title}}" width="200px" height="200px"><br>
{{ $user->Title}}<br>
{{ $user->Content}}<br>
{{ $user->Price}}€<br>
#endif
</div>
</div>
</div>
</body>
Because you did
Plačiau</div>
The name of the variable you need to fetch is product
$object = \DB::table('braclets')->where('BrackID' , request('product'))->first();

Symfony 3 Notice: Object of class Doctrine\ORM\EntityManager could not be converted to int

I am new with Symfony 3 and I am implementing a simple web application. I'm trying to get data from FORM but when get the request and put data in Entity manager instance I got a error, let me explain with code:
This is the Controller (DefaultController)
namespace Database\TestBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Database\TestBundle\Entity\Products;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class DefaultController extends Controller
{
public function addAction(Request $request)
{
$product = new Products();
$form = $this->createFormBuilder($product)
->add('name', TextType::class)
->add('price', TextType::class)
->add('description', TextareaType::class)
->add('save', SubmitType::class, array('label' => 'Save Product'))
->getForm();
$form->handleRequest($request);
if($form->isValid())
{
$product = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em-flush(); //I got the error in this line
return $this->redirect($this->generateUrl('database_test_list'));
}
return $this->render('DatabaseTestBundle:Default:add.html.twig', array(
'form' => $form->createView()));
}
}
This is my Entity (Products)
namespace Database\TestBundle\Entity;
/**
* Products
*/
class Products
{
/**
* #var int
*/
private $id;
/**
* #var string
*/
private $name;
/**
* #var int
*/
private $price;
/**
* #var string
*/
private $description;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Products
*/
public function setName($name)
{
$this->name= $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set price
*
* #param integer $price
*
* #return Products
*/
public function setPrice($price)
{
$this->price= $price;
return $this;
}
/**
* Get price
*
* #return int
*/
public function getPrice()
{
return $this->price;
}
/**
* Set description
*
* #param string $description
*
* #return Products
*/
public function setDescription($description)
{
$this->description= $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
}
This is my View (add)
{% extends '::frontend.html.twig' %}
{% block title %}List of Products{% endblock %}
{% block body %}
<h1 class="clase">Add Product</h1>
<hr>
Return to list
<br/>
<br/>
{{ form_start(form, {'attr': {'class': 'form-horizontal'}}) }}
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label class="col-sm-1 control-label required" for="form_name">Name</label>
<div class="col-sm-3">
{{form_widget(form.name, {'attr': {'class': 'form-control col-md-12'}})}}
</div>
</div>
<div class="form-group">
<label class="col-sm-1 control-label required" for="form_price">Price</label>
<div class="col-sm-3">
{{form_widget(form.price, {'attr': {'class': 'form-control col-md-12'}})}}
</div>
</div>
<div class="form-group">
<label class="col-sm-1 control-label required" for="form_description">Description</label>
<div class="col-sm-3">
{{form_widget(form.description, {'attr': {'class': 'form-control col-md-12'}})}}
</div>
</div>
<hr/>
{{form_widget(form.save, {'attr': {'class': 'btn btn-default'}})}}
</p>
</div>
</div>
{{ form_end(form) }}
{% endblock %}
And this is the Error Message:
Stack Trace
in src\Database\TestBundle\Controller\DefaultController.php at line 48
46 $em = $this->container->get('doctrine')->getManager();
47 $em->persist($product);
48 $em-flush();
49 return $this->redirect($this->generateUrl('database_test_list'));
at ErrorHandler ->handleError ('8', 'Object of class Doctrine\ORM\EntityManager could not be converted to int',
'C:\xampp\htdocs\taller_symfony\src\Database\TestBundle\Controller\DefaultController.php', '48', array('request' => object(Request), 'producto' => object(Productos), 'form' => object(Form), 'em' => object(EntityManager)))
in src\Database\TestBundle\Controller\DefaultController.php at line 48
Somebody has any idea regarding this error?? Anyone can give me a hand with this please, thanks a lot.
You have syntax error, which is > sign missing.
You have:
$em-flush();
while it should be:
$em->flush();
PHP didn't throw syntax error because it's actually correct PHP syntax, but not the one that you were expected it to be. You tried to make arithmetical (subtraction) operation on object.

How to add html to the form field. Symfony2

How add html element to the form field. How? The reasoning below is wrong, because it outputs my div in the "input" field, instead of inserting pure html between form fields. I want instead of input, to display html code, which would load images. I mean i have ManyToMany relation between images and users. When i have data transformer, which generates strings:
"<img src=\"{{ asset( 'bundles/meeting/images/uploads/".$img->getPath()."') }}\" height=\"200\" />". I would like to insert these strings between User form fields, which should finally display images.
C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\Entity\User.php
/**
* User
*
* #ORM\Table(name="tuser")
* #ORM\Entity()
*/
class User implements AdvancedUserInterface, \Serializable
...
/**
* #ORM\ManyToMany(targetEntity="\MeetingBundle\Entity\Image")
* #ORM\JoinTable(name="tUserImgUni",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="image_id", referencedColumnName="id")}
* )
*/
private $imgsuni;
....
/**
* Constructor
*/
public function __construct()
{
$this->imgsuni = new ArrayCollection();
}
...
/**
* Add imgsuni
*
* #param \MeetingBundle\Entity\Image $imgsuni
*
* #return User
*/
public function addImgsuni(\MeetingBundle\Entity\Image $image)
{
$this->imgsuni[] = $image;
return $this;
}
....
C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\Entity\Image.php
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class Image
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
public $path;
...
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
..
/**
* Called after entity persistence
*
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
return;
}
$this->file->move(
'C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\web\bundles\meeting\images\uploads',
$this->path
);
$this->file = null;
}
C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\Form\UserType.php
...
use MeetingBundle\Form\DataTransformer\ImageDataTransformer;
class UserType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$em = $options['em'];
$trans = new ImageDataTransformer($em);
$builder
->add('username')
->add(
$builder
->create('imgsuni', 'text')
->addModelTransformer($trans)
)
...
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MeetingBundle\Entity\User'
))
->setRequired(['em'])
->setAllowedTypes('em', 'Doctrine\ORM\EntityManager')
;
}
C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\Form\DataTransformer\ImageDataTransformer.php
<?php
namespace MeetingBundle\Form\DataTransformer;
use MeetingBundle\Entity\Image;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\DataTransformerInterface;
class ImageDataTransformer implements DataTransformerInterface
{
/**
* #var EntityManager
*/
private $em;
/**
* #param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* Transforms an objects (Tags) to a string.
*/
public function transform($imgs)
{
if (null === $imgs) {
return "";
}
$output = [];
foreach ($imgs as $img) {
$output[] =
"<img src=\"{{ asset( 'bundles/meeting/images/uploads/".$img->getPath()."') }}\" height=\"200\" />"
;
}
return join(', ', $output);
}
}
For instance i have user with id=21 and image id=1.
My transformer generates string:
<img src="{{ asset( 'bundles/meeting/images/uploads/a4d7fb6b1282815d41e2015bfe6b3334f0833063.png') }}" height="200" />
i want that this string would be inserted as html code instead of beeing displayed in input of the form.
C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\Controller\UserController.php
/**
* Displays a form to edit an existing User entity.
*
* #Route("/{id}/edit", name="user_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, User $user)
{
$em = $this->getDoctrine()->getManager();
$deleteForm = $this->createDeleteForm($user);
$editForm = $this->createForm(new UserType(), $user, ['em' => $em ]);
$editForm->add('submit', 'submit', array(
'label' => 'Update details',
));
$image = new Image();
$imageForm=$this->createForm(new ImageType(), $image);
$imageForm->add('submit', 'submit', array('label' => 'Upload image'));
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirectToRoute('user_edit', array('id' => $user->getId()));
}
$imageForm->handleRequest($request);
if ($imageForm->isSubmitted() && $imageForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($image);
$em->flush();
//$image_id=$image->getId();
$user->addImgsuni($image);
$em->persist($user);
$em->flush(); //MeetingBundle::
return $this->redirectToRoute('user_edit', array('id' => $user->getId()));
}
return $this->render('MeetingBundle::user/edit.html.twig', array(
'user' => $user,
'edit_form' => $editForm->createView(),
'image_form' => $imageForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\Resources\views\Image\edit.html.twig
{% extends "MeetingBundle::layout.html.twig" %}
{% block body %}
<h1>User edit</h1>
{{ form_start(edit_form) }}
{{ form_widget(edit_form) }}
{{ form_end(edit_form) }}
<br>
{{ form(image_form) }}
<ul>
<li>
Back to the list
</li>
<br>
<li>
{{ form_start(delete_form) }}
{{ form_end(delete_form) }}
</li>
</ul>
{% endblock %}
url: http://localhost:8000/user/21/edit
This displays form with Imgsuni input field with the following content:
<img src="{{ asset( 'bundles/meeting/images/uploads/a4d7fb6b1282815d41e2015bfe6b3334f0833063.png') }}" height="200" />
The way is to add html to some field in Image entity, said named "htmlimg". Than to display contents of the field in twig template using {{ image.htmlimg }}. This generates: <img src="{{ asset( 'bundles/meeting/images/uploads/a4d7fb6b1282815d41e2015bfe6b3334f0833063.png') }}" height="200" /> and displays images.

Having trouble understanding links in laravel 4

I have a problem with link_to_action in laravel 4
In laravel 3 i would show a link like
{{ HTML::link_to_action('user/create', 'Create User') }}
But since I've switched to laravel 4 I'm creating my controllers like this UserController but when I try to use the HTML
{{ HTML::linkAction('user/create', 'Create User') }}
It gives me and error that action doesn't exist even though there's a method named create.
Any help would be greatly appreciated.
And here's my controller
<?php
class UserController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
// L3
{{ HTML::link_to_action('user#create', 'Create User') }}
// L4
{{ HTML::linkAction('UserController#create', 'Create User') }}
edit:
// I think you missed that entry in your routes.php
Route::resource('user', 'UserController');

Resources