Adding datatables to symfony 3 - data not showing - symfony

I tried installing datatables to my Symfony 3 project. I'm new to this and not sure where I went wrong but the data from my MySQL database are not showing.
I have {{ datatable_render(datatable) }} on my index page but all it shows in a button to add another entry.
This is my controller
namespace AppBundle\Controller;
use AppBundle\Entity\Shrubs;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request;
/**
* Shrub controller.
*
* #Route("shrubs")
*/
class ShrubsController extends Controller
{
/**
* Lists all shrub entities.
*
* #Route("/", name="shrubs_index")
* #Method("GET")
*/
public function indexAction()
{
$datatable = $this->get('app.datatable.shrubs');
$datatable->buildDatatable();
// $em = $this->getDoctrine()->getManager();
// $datatable = $em->getRepository('AppBundle:Shrubs')->findAll();
return $this->render('shrubs/index.html.twig', array(
'datatable' => $datatable,
// 'shrubs' => $shrubs,
));
}
/**
* #Route("/results", name="shrubs_results")
*/
public function indexResultsAction()
{
$datatable = $this->get('app.datatable.shrubs');
$datatable->buildDatatable();
$query = $this->get('shrubs_datatable')->getQueryFrom($datatable);
return $query->getResponse();
}
ShrubDatatable
<?php
namespace AppBundle\Datatables;
use Sg\DatatablesBundle\Datatable\View\AbstractDatatableView;
use Sg\DatatablesBundle\Datatable\View\Style;
/**
* Class ShrubsDatatable
*
* #package AppBundle\Datatables
*/
class ShrubsDatatable extends AbstractDatatableView
{
/**
* {#inheritdoc}
*/
public function buildDatatable(array $options = array())
{
$this->topActions->set(array(
'start_html' => '<div class="row"><div class="col-sm-3">',
'end_html' => '<hr></div></div>',
'actions' => array(
array(
'route' => $this->router->generate('shrubs_new'),
'label' => $this->translator->trans('datatables.actions.new'),
'icon' => 'glyphicon glyphicon-plus',
'attributes' => array(
'rel' => 'tooltip',
'title' => $this->translator->trans('datatables.actions.new'),
'class' => 'btn btn-primary',
'role' => 'button'
),
)
)
));
$this->features->set(array(
'auto_width' => true,
'defer_render' => false,
'info' => true,
'jquery_ui' => false,
'length_change' => true,
'ordering' => true,
'paging' => true,
'processing' => true,
'scroll_x' => false,
'scroll_y' => '',
'searching' => true,
'state_save' => false,
'delay' => 0,
'extensions' => array(),
'highlight' => false,
'highlight_color' => 'red'
));
$this->ajax->set(array(
'url' => $this->router->generate('shrubs_index'),
'type' => 'GET',
'pipeline' => 0
));
$this->options->set(array(
'display_start' => 0,
'defer_loading' => -1,
'dom' => 'lfrtip',
'length_menu' => array(10, 25, 50, 100),
'order_classes' => true,
'order' => array(array(0, 'asc')),
'order_multi' => true,
'page_length' => 10,
'paging_type' => Style::FULL_NUMBERS_PAGINATION,
'renderer' => '',
'scroll_collapse' => false,
'search_delay' => 0,
'state_duration' => 7200,
'stripe_classes' => array(),
'class' => Style::BOOTSTRAP_3_STYLE,
'individual_filtering' => false,
'individual_filtering_position' => 'head',
'use_integration_options' => true,
'force_dom' => false,
'row_id' => 'id'
));
$this->columnBuilder
->add('botanicalname', 'column', array(
'title' => 'Botanicalname',
))
->add('commonname', 'column', array(
'title' => 'Commonname',
))
->add('borderlinehardy', 'column', array(
'title' => 'Borderlinehardy',
))
->add('phpreference', 'column', array(
'title' => 'Phpreference',
))
->add('wetsoil', 'column', array(
'title' => 'Wetsoil',
))
->add('moistsoil', 'column', array(
'title' => 'Moistsoil',
))
->add('peatysoil', 'column', array(
'title' => 'Peatysoil',
))
->add('welldrainedsoil', 'column', array(
'title' => 'Welldrainedsoil',
))
->add('drought', 'column', array(
'title' => 'Drought',
))
->add('claysoil', 'column', array(
'title' => 'Claysoil',
))
->add('sandysoil', 'column', array(
'title' => 'Sandysoil',
))
->add('loamsoil', 'column', array(
'title' => 'Loamsoil',
))
->add('infertilesoil', 'column', array(
'title' => 'Infertilesoil',
))
->add('richsoil', 'column', array(
'title' => 'Richsoil',
))
->add('compactedsoil', 'column', array(
'title' => 'Compactedsoil',
))
->add('cityconditions', 'column', array(
'title' => 'Cityconditions',
))
->add('pollution', 'column', array(
'title' => 'Pollution',
))
->add('salt', 'column', array(
'title' => 'Salt',
))
->add('windy', 'column', array(
'title' => 'Windy',
))
->add('shade', 'column', array(
'title' => 'Shade',
))
->add('partshade', 'column', array(
'title' => 'Partshade',
))
->add('fullsun', 'column', array(
'title' => 'Fullsun',
))
->add('pestproblem', 'column', array(
'title' => 'Pestproblem',
))
->add('id', 'column', array(
'title' => 'Id',
))
->add(null, 'action', array(
'title' => $this->translator->trans('datatables.actions.title'),
'actions' => array(
array(
'route' => 'shrubs_show',
'route_parameters' => array(
'id' => 'id'
),
'label' => $this->translator->trans('datatables.actions.show'),
'icon' => 'glyphicon glyphicon-eye-open',
'attributes' => array(
'rel' => 'tooltip',
'title' => $this->translator->trans('datatables.actions.show'),
'class' => 'btn btn-primary btn-xs',
'role' => 'button'
),
),
array(
'route' => 'shrubs_edit',
'route_parameters' => array(
'id' => 'id'
),
'label' => $this->translator->trans('datatables.actions.edit'),
'icon' => 'glyphicon glyphicon-edit',
'attributes' => array(
'rel' => 'tooltip',
'title' => $this->translator->trans('datatables.actions.edit'),
'class' => 'btn btn-primary btn-xs',
'role' => 'button'
),
)
)
))
;
}
/**
* {#inheritdoc}
*/
public function getEntity()
{
return 'AppBundle\Entity\Shrubs';
}
/**
* {#inheritdoc}
*/
public function getName()
{
return 'shrubs_datatable';
}
}
Entity\Shrubs
<?php
namespace AppBundle\Entity;
/**
* Shrubs
*/
class Shrubs
{
/**
* #var string
*/
private $botanicalname;
/**
* #var string
*/
private $commonname;
/**
* #var string
*/
private $borderlinehardy;
/**
* #var string
*/
private $phpreference;
/**
* #var string
*/
private $wetsoil;
/**
* #var string
*/
private $moistsoil;
/**
* #var string
*/
private $peatysoil;
/**
* #var string
*/
private $welldrainedsoil;
/**
* #var string
*/
private $drought;
/**
* #var string
*/
private $claysoil;
/**
* #var string
*/
private $sandysoil;
/**
* #var string
*/
private $loamsoil;
/**
* #var string
*/
private $infertilesoil;
/**
* #var string
*/
private $richsoil;
/**
* #var string
*/
private $compactedsoil;
/**
* #var string
*/
private $cityconditions;
/**
* #var string
*/
private $pollution;
/**
* #var string
*/
private $salt;
/**
* #var string
*/
private $windy;
/**
* #var string
*/
private $shade;
/**
* #var string
*/
private $partshade;
/**
* #var string
*/
private $fullsun;
/**
* #var string
*/
private $pestproblem;
/**
* #var integer
*/
private $id;
/**
* Set botanicalname
*
* #param string $botanicalname
*
* #return Shrubs
*/
public function setBotanicalname($botanicalname)
{
$this->botanicalname = $botanicalname;
return $this;
}
/**
* Get botanicalname
*
* #return string
*/
public function getBotanicalname()
{
return $this->botanicalname;
}
/**
* Set commonname
*
* #param string $commonname
*
* #return Shrubs
*/
public function setCommonname($commonname)
{
$this->commonname = $commonname;
return $this;
}
/**
* Get commonname
*
* #return string
*/
public function getCommonname()
{
return $this->commonname;
}
/**
* Set borderlinehardy
*
* #param string $borderlinehardy
*
* #return Shrubs
*/
public function setBorderlinehardy($borderlinehardy)
{
$this->borderlinehardy = $borderlinehardy;
return $this;
}
/**
* Get borderlinehardy
*
* #return string
*/
public function getBorderlinehardy()
{
return $this->borderlinehardy;
}
/**
* Set phpreference
*
* #param string $phpreference
*
* #return Shrubs
*/
public function setPhpreference($phpreference)
{
$this->phpreference = $phpreference;
return $this;
}
/**
* Get phpreference
*
* #return string
*/
public function getPhpreference()
{
return $this->phpreference;
}
/**
* Set wetsoil
*
* #param string $wetsoil
*
* #return Shrubs
*/
public function setWetsoil($wetsoil)
{
$this->wetsoil = $wetsoil;
return $this;
}
/**
* Get wetsoil
*
* #return string
*/
public function getWetsoil()
{
return $this->wetsoil;
}
/**
* Set moistsoil
*
* #param string $moistsoil
*
* #return Shrubs
*/
public function setMoistsoil($moistsoil)
{
$this->moistsoil = $moistsoil;
return $this;
}
/**
* Get moistsoil
*
* #return string
*/
public function getMoistsoil()
{
return $this->moistsoil;
}
/**
* Set peatysoil
*
* #param string $peatysoil
*
* #return Shrubs
*/
public function setPeatysoil($peatysoil)
{
$this->peatysoil = $peatysoil;
return $this;
}
/**
* Get peatysoil
*
* #return string
*/
public function getPeatysoil()
{
return $this->peatysoil;
}
/**
* Set welldrainedsoil
*
* #param string $welldrainedsoil
*
* #return Shrubs
*/
public function setWelldrainedsoil($welldrainedsoil)
{
$this->welldrainedsoil = $welldrainedsoil;
return $this;
}
/**
* Get welldrainedsoil
*
* #return string
*/
public function getWelldrainedsoil()
{
return $this->welldrainedsoil;
}
/**
* Set drought
*
* #param string $drought
*
* #return Shrubs
*/
public function setDrought($drought)
{
$this->drought = $drought;
return $this;
}
/**
* Get drought
*
* #return string
*/
public function getDrought()
{
return $this->drought;
}
/**
* Set claysoil
*
* #param string $claysoil
*
* #return Shrubs
*/
public function setClaysoil($claysoil)
{
$this->claysoil = $claysoil;
return $this;
}
/**
* Get claysoil
*
* #return string
*/
public function getClaysoil()
{
return $this->claysoil;
}
/**
* Set sandysoil
*
* #param string $sandysoil
*
* #return Shrubs
*/
public function setSandysoil($sandysoil)
{
$this->sandysoil = $sandysoil;
return $this;
}
/**
* Get sandysoil
*
* #return string
*/
public function getSandysoil()
{
return $this->sandysoil;
}
/**
* Set loamsoil
*
* #param string $loamsoil
*
* #return Shrubs
*/
public function setLoamsoil($loamsoil)
{
$this->loamsoil = $loamsoil;
return $this;
}
/**
* Get loamsoil
*
* #return string
*/
public function getLoamsoil()
{
return $this->loamsoil;
}
/**
* Set infertilesoil
*
* #param string $infertilesoil
*
* #return Shrubs
*/
public function setInfertilesoil($infertilesoil)
{
$this->infertilesoil = $infertilesoil;
return $this;
}
/**
* Get infertilesoil
*
* #return string
*/
public function getInfertilesoil()
{
return $this->infertilesoil;
}
/**
* Set richsoil
*
* #param string $richsoil
*
* #return Shrubs
*/
public function setRichsoil($richsoil)
{
$this->richsoil = $richsoil;
return $this;
}
/**
* Get richsoil
*
* #return string
*/
public function getRichsoil()
{
return $this->richsoil;
}
/**
* Set compactedsoil
*
* #param string $compactedsoil
*
* #return Shrubs
*/
public function setCompactedsoil($compactedsoil)
{
$this->compactedsoil = $compactedsoil;
return $this;
}
/**
* Get compactedsoil
*
* #return string
*/
public function getCompactedsoil()
{
return $this->compactedsoil;
}
/**
* Set cityconditions
*
* #param string $cityconditions
*
* #return Shrubs
*/
public function setCityconditions($cityconditions)
{
$this->cityconditions = $cityconditions;
return $this;
}
/**
* Get cityconditions
*
* #return string
*/
public function getCityconditions()
{
return $this->cityconditions;
}
/**
* Set pollution
*
* #param string $pollution
*
* #return Shrubs
*/
public function setPollution($pollution)
{
$this->pollution = $pollution;
return $this;
}
/**
* Get pollution
*
* #return string
*/
public function getPollution()
{
return $this->pollution;
}
/**
* Set salt
*
* #param string $salt
*
* #return Shrubs
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Get salt
*
* #return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* Set windy
*
* #param string $windy
*
* #return Shrubs
*/
public function setWindy($windy)
{
$this->windy = $windy;
return $this;
}
/**
* Get windy
*
* #return string
*/
public function getWindy()
{
return $this->windy;
}
/**
* Set shade
*
* #param string $shade
*
* #return Shrubs
*/
public function setShade($shade)
{
$this->shade = $shade;
return $this;
}
/**
* Get shade
*
* #return string
*/
public function getShade()
{
return $this->shade;
}
/**
* Set partshade
*
* #param string $partshade
*
* #return Shrubs
*/
public function setPartshade($partshade)
{
$this->partshade = $partshade;
return $this;
}
/**
* Get partshade
*
* #return string
*/
public function getPartshade()
{
return $this->partshade;
}
/**
* Set fullsun
*
* #param string $fullsun
*
* #return Shrubs
*/
public function setFullsun($fullsun)
{
$this->fullsun = $fullsun;
return $this;
}
/**
* Get fullsun
*
* #return string
*/
public function getFullsun()
{
return $this->fullsun;
}
/**
* Set pestproblem
*
* #param string $pestproblem
*
* #return Shrubs
*/
public function setPestproblem($pestproblem)
{
$this->pestproblem = $pestproblem;
return $this;
}
/**
* Get pestproblem
*
* #return string
*/
public function getPestproblem()
{
return $this->pestproblem;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
I went through a tutorial and auto generated the datatables so I'm not sure what other info is needed. Please let me know and I'll add it.

Related

Not exprexted behaviour on symfony datatransformer

I created a datatransformer to store dates on unixtime on the database but show it as datetime on the form
this is the transformer
class IntegerToTimestampTransformer implements DataTransformerInterface
{
public function transform($timestamp)
{
/**
* This if sentenceis because when eidt $timestamp is a timestamp(unix)
* but when create is a DateTime ¿¿???
*/
if($timestamp instanceof \DateTime){
return $timestamp;
}
return (new \DateTime())->setTimestamp($timestamp);
}
public function reverseTransform($datetime)
{
if ($datetime === null) {
return $datetime;
}
return $datetime->getTimestamp();
}
}
this is the entity
/**
* Popup
*
* #ORM\Table(name="popup")
* #ORM\Entity(repositoryClass="AppBundle\Repository\PopUpRepository")
*/
class Popup
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #Gedmo\Translatable()
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #Gedmo\Translatable()
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var int
*
* #ORM\Column(name="activation_date", type="integer", nullable=true)
*/
private $activationDate;
/**
* #var int
*
* #ORM\Column(name="deactivation_date", type="integer", nullable=true)
*/
private $deactivationDate;
/**
* #var boolean
*
* #ORM\Column(name="active", type="boolean")
*/
private $active;
/**
* #var Collection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Role")
* #ORM\JoinTable(name="popup_role", joinColumns={#ORM\JoinColumn(name="popup_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")})
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
}
/**
* #return int
*/
public function getId(): int
{
return $this->id;
}
/**
* #param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
/**
* #return string
*/
public function getTitle():? string
{
return $this->title;
}
/**
* #param string $title
*/
public function setTitle(string $title): void
{
$this->title = $title;
}
/**
* #return string
*/
public function getDescription(): ?string
{
return $this->description;
}
/**
* #param string $description
*/
public function setDescription(string $description): void
{
$this->description = $description;
}
/**
* #return int
*/
public function getActivationDate(): ?int
{
return $this->activationDate;
}
/**
* #param int $activationDate
*/
public function setActivationDate(int $activationDate): void
{
$this->activationDate = $activationDate;
}
/**
* #return int
*/
public function getDeactivationDate(): ?int
{
return $this->deactivationDate;
}
/**
* #param int $deactivationDate
*/
public function setDeactivationDate(int $deactivationDate): void
{
$this->deactivationDate = $deactivationDate;
}
/**
* #return bool
*/
public function isActive(): ?bool
{
return $this->active;
}
/**
* #param bool $active
*/
public function setActive(bool $active): void
{
$this->active = $active;
}
/**
* Add role
*
* #param Role $role
*
* #return Role
*/
public function addRole(Role $role)
{
$this->roles[] = $role;
return $this;
}
/**
* Remove role
*
* #param Role $role
*/
public function removeRole(Role $role)
{
$this->roles->removeElement($role);
}
/**
* Get role
*
* #return Collection
*/
public function getRoles()
{
return $this->roles;
}
}
and the formtype
class PopupType extends AbstractType
{
private $tranformer;
public function __construct(IntegerToTimestampTransformer $tranformer){
$this->tranformer = $tranformer;
}
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$date_array = [
'label_attr' => [
'class' => 'font-weight-bold'
],
'required' => false
];
if(!$options['edit']){
$date_array['data'] = new \DateTime();
}
$builder
->add('title', TextType::class, [
'label_attr' => [
'class' => 'font-weight-bold'
],
])
->add('description', TextareaType::class, [
'label_attr' => [
'class' => 'font-weight-bold'
],
'required' => false
])
->add('activation_date', DateTimeType::class, $date_array)
->add('deactivation_date', DateTimeType::class,$date_array)
->add('active', CheckboxType::class, [
'label_attr' => [
'class' => 'font-weight-bold'
],
'required' => false
])
->add('roles', EntityType::class, [
'class' => Role::class,
'expanded' => true,
'multiple' => true,
'required' => true,
'label_attr' => [
'class' => 'font-weight-bold'
],
])
;
$builder->get('activation_date')->addModelTransformer($this->tranformer);
$builder->get('deactivation_date')->addModelTransformer($this->tranformer);
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Popup::class,
'edit' => false
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_popup';
}
}
I debugged and I checked that in the transform function when I try to create on the crud the parameter passed to transform is a Datetime the there is no need to transformate the data but when I try to edit the parameter passed to transform is a unixtime integer the the transformation is needed, I don't understant that behaviour.

Symfony3 error with ManyToMany with attributes

We have an error when trying to create a relationship within 2 tables like this
Llamadas -||--|<- LlamadaDerivada ->|--||- PersonaDerivada
And we are trying to create an only one create form with the "LlamadaDerivada" into it.
Inside Llamada entity
<?php
namespace xxxxBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
class Llamada {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="llamada_id_seq", allocationSize=1, initialValue=1)
*/
private $id;
/**
* #var string
* #Assert\Length(
* max = 50,
* maxMessage = "Your first name cannot be longer than {{ limit }} characters",
* )
* #ORM\Column(name="nombre", type="string", length=150, nullable=false)
*/
private $nombre;
/**
*
* #ORM\OneToMany(targetEntity="LlamadaDerivado", mappedBy="llamada")
*/
private $derivados;
function __construct() {
$this->derivados = new ArrayCollection();
}
function getId() {
return $this->id;
}
function getNombre() {
return $this->nombre;
}
function setId($id) {
$this->id = $id;
}
function setNombre($nombre) {
$this->nombre = $nombre;
}
function getDerivados(){
return $this->derivados;
}
function setDerivados($derivados){
$this->derivados = $derivados;
}
}
Then inside LlamadaDerivado Entity we have this
<?php
namespace xxxBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* LlamadaDerivado
*
* #ORM\Table(name="llamada_derivado")
* #ORM\Entity
*/
class LlamadaDerivado
{
/**
* #var \AgendaBundle\Entity\Llamada
*
* #ORM\ManyToOne(targetEntity="AgendaBundle\Entity\Llamada",inversedBy="derivados",cascade={"persist"})
* #ORM\Id
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_llamada", referencedColumnName="id")
* })
*/
private $llamada;
/**
* #var \AgendaBundle\Entity\PersonaDerivado
*
* #ORM\ManyToOne(targetEntity="AgendaBundle\Entity\PersonaDerivado",inversedBy="llamadas",cascade={"persist"})
* #ORM\Id
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_derivado", referencedColumnName="id")
* })
*/
private $derivado;
/**
* #var DateTime
*
* #ORM\Column(name="fecha_derivacion", type="date", nullable=false)
*/
private $fechaDerivacion;
function getLlamada(){
return $this->llamada;
}
function getDerivado(){
return $this->derivado;
}
function getFechaDerivacion() {
return $this->fechaDerivacion;
}
function setLlamada( $llamada) {
$this->llamada = $llamada;
}
function setDerivado( $derivado) {
$this->derivado = $derivado;
}
function setFechaDerivacion($fechaDerivacion) {
$this->fechaDerivacion = $fechaDerivacion;
}
}
And inside PersonaDerivado entity
<?php
namespace xxxBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* ReunionLugar
*
* #ORM\Table(name="persona_derivado")
* #ORM\Entity
*/
class PersonaDerivado
{
public function __construct() {
$this->llamadas = new ArrayCollection();
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="reunion_lugar_id_seq", allocationSize=1, initialValue=1)
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nombre", type="string", length=150, nullable=false)
*/
private $nombre;
/**
* #ORM\OneToMany(targetEntity="LlamadaDerivado", mappedBy="derivado")
*/
private $llamadas;
function getId() {
return $this->id;
}
function getNombre() {
return $this->nombre;
}
function setId($id) {
$this->id = $id;
}
function setNombre($nombre) {
$this->nombre = $nombre;
}
function setLlamadas($llamadas) {
$this->llamadas = $llamadas;
}
}
And the LlamadaType is
class LlamadaDto extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$disabled = $options['disabled'];
$builder
->add('id', HiddenType::class)
->add('nombre', TextType::class, array(
'disabled' => $disabled,
'attr' => ['maxlength'=>'50']
))->add('apellido', TextType::class, array(
'disabled' => $disabled,
'attr' => ['maxlength'=>'50']
))->add('fecha', DateType::class, array(
'format' => 'dd/MM/yyyy',
'disabled' => $disabled,
'widget' => 'single_text',
'attr' => ['class' => 'datepicker']
))->add('hora', TimeType::class, array(
'disabled' => $disabled
))->add('motivo', TextareaType::class, array(
'disabled' => $disabled,
'attr' => ['maxlength'=>'400']
))->add('telefonoContacto', TextType::class, array(
'disabled' => $disabled,
'attr' => ['maxlength'=>'9']
))->add('derivados', EntityType::class, array(
'class' => 'AgendaBundle:PersonaDerivado',
'choice_label' => 'apellidoNombre',
'placeholder' => 'Seleccionar un derivado',
'multiple' => true,
));
}
public function configureOptions(OptionsResolver$resolver) {
$resolver->setDefaults(array('data_class' => Llamada::class));
}
}
Inside the controller we have this code
<?php
/**
* #Route("/Llamada/save",name="saveLlamada")
*/
public function saveLlamadaAction(Request $request) {
$llamadaService = $this->get('llamadaService');
$derivadoService = $this->get('derivadoService');
$form = $this->createForm(LlamadaDto::class);
$form->handleRequest($request);
$editar = TRUE;
$llamada = $form->getData();
$derivados = $request->request->get("llamada_dto")["derivados"];
$derivadosActuales = $derivadoService->getLlamadaDerivados($llamada->getId());
foreach ($derivados as $key1 => $d) {
foreach ($derivadosActuales as $key2 => $da) {
if($da->getDerivado()->getId()==$d){
array_splice($derivados, array_search($d, $derivados),1);
}
}
}
if ($llamadaService->saveLlamada($llamada)) {
$this->addFlash(
'exitoLlamada', 'Datos de llamada guardados exitosamente'
);
$derivadoService->saveDerivados($derivados,$llamada);
} else {
$this->addFlash(
'errorLlamada', 'Disculpe, hubo un error en el registro de la llamada'
);
}
return new RedirectResponse($this->generateUrl('listaLlamadas', array(), UrlGeneratorInterface::RELATIVE_PATH));
}
And the services called are this ones:
public function saveLlamada($llamada ){
try{
if($llamada->getId()){
$this->em->merge($llamada);
}else{
$this->em->persist($llamada);
}
$this->em->flush();
return TRUE;
} catch (Exception $ex){
return FALSE;
}
}
public function saveDerivados($derivados,$llamada){
foreach ($derivados as $key => $derivado) {
$llamadaDerivado = new LlamadaDerivado();
$personaLlamada = $this->getDerivado($derivado);
$llamadaDerivado->setLlamada($llamada);
$llamadaDerivado->setDerivado($personaLlamada);
$llamadaDerivado->setFechaDerivacion(new \DateTime('now', (new \DateTimeZone('America/Argentina/Ushuaia'))));
$this->em->persist($llamadaDerivado);
$this->em->flush();
}
}
This is the error that we are getting:
Uncaught PHP Exception Doctrine\ORM\ORMInvalidArgumentException: "Expected value of type "Doctrine\Common\Collections\Collection|array" for association field "xxxBundle\Entity\Llamada#$derivados", got "xxxBundle\Entity\PersonaDerivado" instead." at project\vendor\doctrine\orm\lib\Doctrine\ORM\ORMInvalidArgumentException.php line 206
We've been 1 week with this.
Many thanks in advance
You can try to use a CollectionType instead of EntityType in your formtype, although I have a piece of code in front of me that works just fine with EntityType and the multiple flag for a OneToMany relationship.
look at Llamada entity, $derivados is an array collection of LlamadaDerivado and in your LlamadaType you make it entityType of AgendaBundle:PersonaDerivado, that is why you got this error. Think to use Collection Type to add everytime all the object LlamadaDerivado to well respect the mapping.

One to One relationship in SonataAdmin

i trying to make admin page for Product which has relationship 1:1 with image.
Product
/**
* #ORM\Entity
* #ORM\Table(name="products")
class Product
{
/**
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
* #ORM\Id
* #var int
*/
private $id = 0;
/**
* #ORM\OneToOne(targetEntity="Image", mappedBy="product")
*/
private $image;
/**
* #return Image
*/
public function getImage(): ?Image
{
return $this->image;
}
/**
* #param Image $image
*/
public function setImage(Image $image)
{
$this->image = $image;
return $this;
}
}
Image
/**
* #ORM\Entity
* #ORM\Table(name="images")
*/
class Image
{
/**
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
* #ORM\Id
* #var int
*/
private $id = 0;
/**
* #ORM\OneToOne(targetEntity="Product", inversedBy="image")
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
*/
private $product;
/**
* #return mixed
*/
public function getProduct()
{
return $this->product;
}
public function setProduct(Product $product)
{
$this->product = $product;
}
}
ProductAdmin
class ProductAdmin extends AbstractAdmin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('image', 'sonata_type_admin', array('label' => 'Okładka', 'by_reference' => false,));
}
ImageAdmin
class ImageAdmin extends AbstractAdmin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('file', 'file', array('label' => 'Okładka', 'required' => false))
->add('path', 'text', array('label' => 'Scieżka do pliku', 'required' => false));
}
I setuped services correctly, but i can't edit product and after saving new one i geting error
unable to find the object with id : 0
Try to not initialize your $id
private $id = 0; // =====> this is a private $id;
You have several mistakes. Let's try to correct your code.
Just follow the tutorials and put right annotation for $id:
/**
* #var integer $id
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
Hope, that this is just a typo with "?Image":
/**
* #return Image
*/
public function getImage() : Image
{
return $this->image;
}
And finally.
/**
* Class ProductAdmin
*/
class ProductAdmin extends AbstractAdmin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('image', 'sonata_type_model_list', [
'btn_add' => true, //Or you can specify a custom label
'btn_list' => 'list button!', //which will be translated
'btn_delete' => false, //or hide the button.
'btn_catalogue' => 'messages', //Custom translation domain for buttons
'label' => 'My image',
], [
'placeholder' => $this->trans('messages.no_images_message'),
'edit' => 'standard',
'inline' => 'standard',
'sortable' => 'id',
])
;
}
}

How can I add thumbnail of an image in sonata admin listmapper

I don´t know how to preview a small image in my listmapper in admin class of an entity. I only see a link to the edit form of the picture, but I want to see a thumbnail of the picture.
This is my entity:
<?php
namespace ExampleBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Translatable\Translatable;
use Application\Sonata\MediaBundle\Entity\Media;
/**
* example
*
* #ORM\Table()
* #ORM\Entity
*/
class example
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #var \Application\Sonata\MediaBundle\Entity\Media
* #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"persist"}, fetch="LAZY")
*/
private $imagenEs;
/**
* #var string
* #var \Application\Sonata\MediaBundle\Entity\Media
* #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"persist"}, fetch="LAZY")
*/
private $imagenEn;
/**
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="titulo", type="string", length=255)
*/
private $titulo;
/**
* #var string
*/
private $tituloEn;
/**
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="texto", type="text")
*/
private $texto;
/**
* #var string
*/
private $textoEn;
/**
* #var boolean
*
* #ORM\Column(name="activo", type="boolean")
*/
private $activo;
/**
* #var integer
*
* #ORM\Column(name="ranking", type="integer")
*/
private $ranking;
/**
* #var string
* #Gedmo\Locale
*/
private $locale;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set imagen
*
* #param string $imagen
* #return BannerHome
*/
public function setImagenEs(Media $imagenEs)
{
$this->imagenEs = $imagenEs;
return $this;
}
/**
* Get imagen
*
* #return string
*/
public function getImagenEs()
{
return $this->imagenEs;
}
/**
* Set imagen
*
* #param string $imagen
* #return BannerHome
*/
public function setImagenEn(Media $imagenEn)
{
$this->imagenEn = $imagenEn;
return $this;
}
/**
* Get imagen
*
* #return string
*/
public function getImagenEn()
{
return $this->imagenEn;
}
/**
* Set titulo
*
* #param string $titulo
* #return BannerHome
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* Set titulo
*
* #param string $titulo
* #return BannerHome
*/
public function setTituloEn($tituloEn)
{
$this->tituloEn = $tituloEn;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTituloEn()
{
return $this->tituloEn;
}
/**
* Set texto
*
* #param string $texto
* #return BannerHome
*/
public function setTexto($texto)
{
$this->texto = $texto;
return $this;
}
/**
* Get texto
*
* #return string
*/
public function getTexto()
{
return $this->texto;
}
/**
* Set texto
*
* #param string $texto
* #return BannerHome
*/
public function setTextoEn($textoEn)
{
$this->textoEn = $textoEn;
return $this;
}
/**
* Get texto
*
* #return string
*/
public function getTextoEn()
{
return $this->textoEn;
}
/**
* Set activoBoolean
*
* #param string $activoBoolean
* #return BannerHome
*/
public function setActivo($activo)
{
$this->activo = $activo;
return $this;
}
/**
* Get activoBoolean
*
* #return string
*/
public function getActivo()
{
return $this->activo;
}
/**
* Set ranking
*
* #param integer $ranking
* #return BannerHome
*/
public function setRanking($ranking)
{
$this->ranking = $ranking;
return $this;
}
/**
* Get ranking
*
* #return integer
*/
public function getRanking()
{
return $this->ranking;
}
public function setTranslatableLocale($locale) {
$this->locale = $locale;
}
}?>
And this is my admin class
<?php
namespace ExampleBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;
class PibeAdmin extends Admin
{
/**
* #param DatagridMapper $datagridMapper
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('id')
->add('titulo')
->add('texto')
->add('activo')
->add('ranking')
;
}
/**
* #param ListMapper $listMapper
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('id')
->add('titulo')
->add('imagenEs') /*With this I see a link to the image, and if I click this link I saw the edit form of the image, but I want a thumbnail*/
->add('activo')
->add('ranking')
->add('_action', 'actions', array(
'actions' => array(
'show' => array(),
'edit' => array(),
'delete' => array(),
)
))
;
}
/**
* #param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$idioma=$this->getRequest()->getLocale();
if($idioma=='es'){
$formMapper
->add('imagenEs', 'sonata_type_model_list', array(
'required' => false,
'label'=>'Imagen Español'
), array(
'link_parameters' => array(
'context' => 'default',
'provider' => 'sonata.media.provider.image'
)
)
)
->add('imagenEn', 'sonata_type_model_list', array(
'required' => false,
'label'=>'Imagen Ingles',
), array(
'link_parameters' => array(
'context' => 'default',
'provider' => 'sonata.media.provider.image'
)
)
)
->add('titulo',null,array('label'=>'Titulo Español'))
->add('tituloEn','text',array('label'=>'Titulo Ingles','data'=>''))
->add('texto','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Texto Español'))
->add('textoEn','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Texto Ingles','data'=>''))
;
}else{
$formMapper
->add('imagenEn', 'sonata_type_model_list', array(
'required' => false,
'label'=>'Imagen Ingles'
), array(
'link_parameters' => array(
'context' => 'default',
'provider' => 'sonata.media.provider.image'
)
)
)
->add('imagenEs', 'sonata_type_model_list', array(
'required' => false,
'label'=>'Imagen Español'
), array(
'link_parameters' => array(
'context' => 'default',
'provider' => 'sonata.media.provider.image'
)
)
)
->add('tituloEn','text',array('label'=>'Titulo Ingles','data'=>''))
->add('titulo',null,array('label'=>'Titulo Español'))
->add('textoEn','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Texto Ingles','data'=>''))
->add('texto','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Texto Español'))
;
}
$formMapper
->add('activo')
->add('ranking')
;
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
if($idioma=='es' && $this->getSubject()->getId()!=null){
//$titoriginal=$em->getRepository('HomeBundle:ImagenesHome')->find($this->getSubject()->getId());
// $titoriginal->setTranslatableLocale('en');
//$em->refresh($titoriginal);
//buscamos su traduccion en la tabal de traducciones.
$repository = $em->getRepository('Gedmo\Translatable\Entity\Translation');
$translations = $repository->findTranslations($this->getSubject());
//rellenamos el campo con la traduccion.
if(count($translations)>0){
$formMapper->get('tituloEn')->setData($translations['en']['titulo']);
$formMapper->get('textoEn')->setData($translations['en']['texto']);
};
}else if($idioma=='en' && $this->getSubject()->getId()!=null){
$titoriginal=$em->getRepository('PibeBundle:Pibe')->find($this->getSubject()->getId());
//cambiamos el locale a 'es' para coger el texto en español
$titoriginal->setTranslatableLocale('en');
$em->refresh($titoriginal);
//una vez que lo cogemos, volvemos a cambiar el locale a 'en'
$formMapper->get('tituloEn')->setData($titoriginal->getTitulo());
$formMapper->get('textoEn')->setData($titoriginal->getTexto());
$titoriginal->setTranslatableLocale('es');
$em->refresh($titoriginal);
}
}
/**
* #param ShowMapper $showMapper
*/
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->add('id')
->add('titulo')
->add('texto')
->add('activo')
->add('ranking')
;
}
public function prePersist($object) {
$container = $this->getConfigurationPool()->getContainer();
$entityManager = $container->get('doctrine.orm.entity_manager');
//insertar en español.
$object->setTitulo($object->getTitulo());
$object->setTexto($object->getTexto());
$object->setTranslatableLocale('es');
$entityManager->persist($object);
$entityManager->flush();
//insertar en ingles.
$object->setTitulo($object->getTituloEn());
$object->setTexto($object->getTextoEn());
$object->setTranslatableLocale('en');
$entityManager->persist($object);
$entityManager->flush();
}
public function preUpdate($object) {
$container = $this->getConfigurationPool()->getContainer();
$entityManager = $container->get('doctrine.orm.entity_manager');
//insertar en español.
$object->setTitulo($object->getTitulo());
$object->setTexto($object->getTexto());
$object->setTranslatableLocale('es');
$entityManager->persist($object);
$entityManager->flush();
//insertar en ingles.
$object->setTitulo($object->getTituloEn());
$object->setTexto($object->getTextoEn());
$object->setTranslatableLocale('en');
$entityManager->persist($object);
$entityManager->flush();
}
}
Where it says "Imagen Es" I want the thumbnail of the image.
$listMapper
->add('thumb', null, array(
'template' => "ExampleBundle:Pibe:list_thumb.html.twig")
)
On list_thumb.html.twig
{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
{% block field %}
{# {{ dump() }} you can dump all variables here #}
{# {{ value }} will return the value of getImagenEs() #}
<img class="img-responsive" alt="{{ object.name }}" src="{{ asset('path/to/uploadfolder/' ~ object.filepath) }}" /> {# or you can use a twig filter with your own logic #}
{% endblock field %}
I believe this is a more up 2 date answer :
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('title')
->add('image', 'string', ['template' => 'SonataMediaBundle:MediaAdmin:list_image.html.twig'])
->add('updatedAt')
->add('_action', null, ['actions' =>
[
'edit' => [],
'delete' => []
], 'label' => 'Actions']);
}

Symfony2 - Doctrine2 - ManyToOne relationship / Expected argument of type "Doctrine\Common\Collections\Collection", "Proxies\...Entity...Proxy" given

I'm trying to build the "edit" controller/view but i encounter this error. From i've read it could be an asociation problem, and i've tried to fix it but i don't know what it's wrong with it. It supposed to return a collection but i don't even know what "proxy" means and how it's getting it.
The entity for which i'm building the edit view:
<?php
namespace Monse\WebBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Monse\WebBundle\Entity\BasedeDatos
*
* #ORM\Table()
* #ORM\Entity
*/
class BasedeDatos
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Monse\WebBundle\Entity\ServidoresBD")
* #ORM\JoinColumn(name="servidores_id", referencedColumnName="id",nullable=false)
*
*/
private $servidorBD;
/**
* #var string $nombreBD
*
* #ORM\Column(name="nombreBD", type="string", length=255,unique=true)
*/
private $nombreBD;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set servidorBD
*
* #param integer $servidorBD
*/
public function setServidorBD(\Monse\WebBundle\Entity\ServidoresBD $servidorBD)
{
$this->servidorBD = $servidorBD;
}
/**
* Get servidorBD
*
* #return integer
*/
public function getServidorBD()
{
return $this->servidorBD;
}
/**
* Set nombreBD
*
* #param string $nombreBD
*/
public function setNombreBD($nombreBD)
{
$this->nombreBD = $nombreBD;
}
/**
* Get nombreBD
*
* #return string
*/
public function getNombreBD()
{
return $this->nombreBD;
}
public function __construct()
{
$this->servidorBD = new Doctrine\Common\Collections\ArrayCollection();
}
}
FormType:
<?php
namespace Monse\WebBundle\Form;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class BasedeDatosType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('ServidorBD','entity',
array ('class' => 'MonseWebBundle:ServidoresBD',
'multiple' => true,
'required' => true,
'label' => 'Servidor de Base de Datos: ',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.url', 'ASC');
},
))
->add('nombreBD','text', array( 'required' => true, 'label' => 'Nombre Base de Datos: '))
->add('UsuarioBD','entity',array('class' => 'MonseWebBundle:UsuariosBD','multiple' => true,
'required' => true, 'label' => 'Usuario Asociado: ',
'property_path' => false,
'query_builder' => function (EntityRepository $er){
return $er->createQueryBuilder('s')
->orderBy ('s.usuario','ASC'); },))
;
}
public function getName()
{
return 'basededatos';
}
}
The entity responsible for the problem (i think):
<?php
namespace Monse\WebBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Monse\WebBundle\Entity\ServidoresBD
*
* #ORM\Table()
* #ORM\Entity
*/
class ServidoresBD
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $url
*
* #ORM\Column(name="url", type="string", length=255)
*/
private $url;
/**
*
* #ORM\OneToOne (targetEntity="Monse\WebBundle\Entity\Dominios")
* #ORM\JoinColumn(name="dominio_id", referencedColumnName="id",nullable=false,unique=true)
*/
private $dominio;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set dominio
*
* #param integer $dominio
*/
public function setDominio(\Monse\WebBundle\Entity\Dominios $dominio)
{
$this->dominio = $dominio;
}
/**
* Get dominio
*
* #return integer
*/
public function getDominio()
{
return $this->dominio;
}
/**
* Set url
*
* #param string $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
public function __toString()
{
return $this->getUrl();
}
}
Form Type:
<?php
namespace Monse\WebBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class ServidoresBDType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('url')
->add('dominio', 'collection', array('type' => new DominiosType()));
;
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Monse\WebBundle\Entity\ServidoresBD'
);
}
public function getName()
{
return 'issue_selector';
}
}
Where should i add the arraycollection to be returned? How do i prevent this from happening again? I'm sorry if this is an stupid question, i'm trying to learn.
I changed the two "multiple" attributes to false in the first form type.

Resources