0

Estoy queriendo hacer un formtype de Symfony 3 con la selección de una sucursal según el premio elegido. Creando un formtype para Exchange obtengo de promotesucursal todos los datos pero no sé cómo obtener solo los relacionados a esa promote.

Dejo mis entidades:

Promote.php

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\JoinTable;
use Doctrine\ORM\Mapping\JoinColumn;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * Promote
 *
 * @ORM\Table(name="promote")
 * @ORM\Entity
 * @UniqueEntity("name", message="Este Nombre ya existe")
 */
class Promote
{
    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=25, nullable=true, unique=true)
     */
    private $name;

    /**
     * @ManyToOne(targetEntity="Subcategoria", inversedBy="promotes")
     * @JoinColumn(name="category_id", referencedColumnName="id")
     */
    private $category_id;

    /** @ORM\OneToMany(targetEntity="AppBundle\Entity\PromoteSucursal", mappedBy="promote") */
    protected $promoteSucursal;


    /**
     * @var string
     *
     * @ORM\Column(name="description", type="string", length=255, nullable=true)
     */
    private $description;

    /**
     * @var boolean
     *
     * @ORM\Column(name="enabled", type="boolean", nullable=true)
     */
    private $enabled = true;


    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;



    /**
     * Set name
     *
     * @param string $name
     *
     * @return Promote
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return Promote
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set enabled
     *
     * @param boolean $enabled
     *
     * @return Promote
     */
    public function setEnabled($enabled)
    {
        $this->enabled = $enabled;

        return $this;
    }

    /**
     * Get enabled
     *
     * @return boolean
     */
    public function getEnabled()
    {
        return $this->enabled;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }


    /**
     * Add promoteSucursal
     *
     * @param \AppBundle\Entity\PromoteSucursal $promoteSucursal
     *
     * @return Promote
     */
    public function addPromoteSucursal(\AppBundle\Entity\PromoteSucursal $promoteSucursal)
    {
        $this->promoteSucursal[] = $promoteSucursal;

        return $this;
    }

    /**
     * Remove promoteSucursal
     *
     * @param \AppBundle\Entity\PromoteSucursal $promoteSucursal
     */
    public function removePromoteSucursal(\AppBundle\Entity\PromoteSucursal $promoteSucursal)
    {
        $this->promoteSucursal->removeElement($promoteSucursal);
    }

    /**
     * Get promoteSucursal
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPromoteSucursal()
    {
        return $this->promoteSucursal;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->promoteSucursal = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function __toString()
    {
        return (string) $this->getName()  ;
    }

}

Sucursal.php

    <?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;


/**
 * Sucursal
 *
 * @ORM\Table(name="sucursal")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\SucursalRepository")
 * @UniqueEntity("name", message="Este Nombre ya existe")
 */
class Sucursal
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

        /**
         * @var int
         *
         * @ORM\Column(name="foreign_id", type="integer", nullable=true)
         */
        private $foreign_id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=40, unique=true)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="farmaceutico", type="string", length=150, nullable=true)
     */
    private $farmaceutico;

    /**
     * @var string
     *
     * @ORM\Column(name="horario", type="string", length=150, nullable=true)
     */
    private $horario;

    /**
     * @var string
     *
     * @ORM\Column(name="telefono", type="string", length=100)
     */
    private $telefono;

    /**
     * @var string
     *
     * @ORM\Column(name="latgeo", type="string", length=150, nullable=true)
     */
    private $latgeo;


    /**
     * @var string
     *
     * @ORM\Column(name="image_path", type="string", length=255, nullable=true)
     */
    private $image_path;

    /**
     * @var string $image_path
     * @Assert\File( maxSize = "1024k", mimeTypesMessage = "Por favor selccionar una Imágen menor a 1 MB")
     */
    private $image;

    /**
     * @var boolean
     *
     * @ORM\Column(name="enabled", type="boolean", nullable=false)
     */
    private $enabled = true;

    /** @ORM\OneToMany(targetEntity="AppBundle\Entity\PromoteSucursal", mappedBy="sucursal") */
    protected $promoteSucursal;
    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Sucursal
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set farmaceutico
     *
     * @param string $farmaceutico
     *
     * @return Sucursal
     */
    public function setFarmaceutico($farmaceutico)
    {
        $this->farmaceutico = $farmaceutico;

        return $this;
    }

    /**
     * Get farmaceutico
     *
     * @return string
     */
    public function getFarmaceutico()
    {
        return $this->farmaceutico;
    }

    /**
     * Set horario
     *
     * @param string $horario
     *
     * @return Sucursal
     */
    public function setHorario($horario)
    {
        $this->horario = $horario;

        return $this;
    }

    /**
     * Get horario
     *
     * @return string
     */
    public function getHorario()
    {
        return $this->horario;
    }

    /**
     * Set telefono
     *
     * @param string $telefono
     *
     * @return Sucursal
     */
    public function setTelefono($telefono)
    {
        $this->telefono = $telefono;

        return $this;
    }

    /**
     * Get telefono
     *
     * @return string
     */
    public function getTelefono()
    {
        return $this->telefono;
    }

    /**
     * Set latgeo
     *
     * @param string $latgeo
     *
     * @return Sucursal
     */
    public function setLatgeo($latgeo)
    {
        $this->latgeo = $latgeo;

        return $this;
    }

    /**
     * Get latgeo
     *
     * @return string
     */
    public function getLatgeo()
    {
        return $this->latgeo;
    }


    public function setImage($image)
    {
        $this->image = $image;
    }

    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set imagePath
     *
     * @param string $imagePath
     *
     * @return Sucursal
     */
    public function setImagePath($imagePath)
    {
        $this->image_path = $imagePath;

        return $this;
    }

    /**
     * Get imagePath
     *
     * @return string
     */
    public function getImagePath()
    {
        return $this->image_path;
    }

    /**
     * Set enabled
     *
     * @param boolean $enabled
     *
     * @return Sucursal
     */
    public function setEnabled($enabled)
    {
        $this->enabled = $enabled;

        return $this;
    }

    /**
     * Get enabled
     *
     * @return boolean
     */
    public function getEnabled()
    {
        return $this->enabled;
    }

    /**
     * Set foreignId
     *
     * @param integer $foreignId
     *
     * @return Sucursal
     */
    public function setForeignId($foreignId)
    {
        $this->foreign_id = $foreignId;

        return $this;
    }

    /**
     * Get foreignId
     *
     * @return integer
     */
    public function getForeignId()
    {
        return $this->foreign_id;
    }

    /**
     * Add promoteSucursal
     *
     * @param \AppBundle\Entity\PromoteSucursal $promoteSucursal
     *
     * @return Sucursal
     */
    public function addPromoteSucursal(\AppBundle\Entity\PromoteSucursal $promoteSucursal)
    {
        $this->promoteSucursal[] = $promoteSucursal;

        return $this;
    }

    /**
     * Remove promoteSucursal
     *
     * @param \AppBundle\Entity\PromoteSucursal $promoteSucursal
     */
    public function removePromoteSucursal(\AppBundle\Entity\PromoteSucursal $promoteSucursal)
    {
        $this->promoteSucursal->removeElement($promoteSucursal);
    }

    /**
     * Get promoteSucursal
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPromoteSucursal()
    {
        return $this->promoteSucursal;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->promoteSucursal = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function __toString()
    {
        return (string) $this->getName()  ;
    }

}

PromoteSucursal.php

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\OneToMany;

/**
 * PromoteSucursal
 *
 * @ORM\Table(name="promote_sucursal")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PromoteSucursalRepository")
 */
class PromoteSucursal
{

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Promote", inversedBy="promoteSucursal")
     * @ORM\JoinColumn(name="promote_id", referencedColumnName="id", nullable=false)
     */
    protected $promote;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Sucursal", inversedBy="promoteSucursal")
     * @ORM\JoinColumn(name="sucursal_id", referencedColumnName="id", nullable=false)
     */
    protected $sucursal;

    /** @ORM\OneToMany(targetEntity="AppBundle\Entity\PromoteExchange", mappedBy="promote_sucursal") */
    protected $promote_exchange;



        /**
     * Set promote
     *
     * @param \AppBundle\Entity\Promote $promote
     *
     * @return PromoteSucursal
     */
    public function setPromote(\AppBundle\Entity\Promote $promote)
    {
        $this->promote = $promote;

        return $this;
    }

    /**
     * Get promote
     *
     * @return \AppBundle\Entity\Promote
     */
    public function getPromote()
    {
        return $this->promote;
    }



    /**
     * Set sucursal
     *
     * @param \AppBundle\Entity\Sucursal $sucursal
     *
     * @return PromoteSucursal
     */
    public function setSucursal(\AppBundle\Entity\Sucursal $sucursal)
    {
        $this->sucursal = $sucursal;

        return $this;
    }

    /**
     * Get sucursal
     *
     * @return \AppBundle\Entity\Sucursal
     */
    public function getSucursal()
    {
        return $this->sucursal;
    }



    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->promote_exchange = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add promoteExchange
     *
     * @param \AppBundle\Entity\PromoteExchange $promoteExchange
     *
     * @return PromoteSucursal
     */
    public function addPromoteExchange(\AppBundle\Entity\PromoteExchange $promoteExchange)
    {
        $this->promote_exchange[] = $promoteExchange;

        return $this;
    }

    /**
     * Remove promoteExchange
     *
     * @param \AppBundle\Entity\PromoteExchange $promoteExchange
     */
    public function removePromoteExchange(\AppBundle\Entity\PromoteExchange $promoteExchange)
    {
        $this->promote_exchange->removeElement($promoteExchange);
    }

    /**
     * Get promoteExchange
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPromoteExchange()
    {
        return $this->promote_exchange;
    }

    public function __toString()
    {
        return (string) $this->getSucursal()  ;
    }
}

PromoteExchange.php

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\JoinColumn;
use Doctrine\ORM\Mapping\JoinTable;

/**
 * PromoteExchange
 *
 * @ORM\Table(name="promote_exchange")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PromoteExchangeRepository")
 */
class PromoteExchange
{


    /**
     * @var string
     *
     * @ORM\Column(name="code", type="string", length=255)
     */
    private $code;

    /**
     * @ORM\Id()
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="promoteExchange")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
     */
    protected $user;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\PromoteSucursal", inversedBy="promote_exchange")
     * @ORM\JoinColumn(name="promote_sucursal_id", referencedColumnName="id", nullable=false)
     */
    protected $promote_sucursal;



        /**
     * Set code
     *
     * @param string $code
     *
     * @return PromoteExchange
     */
    public function setCode($code)
    {
        $this->code = $code;

        return $this;
    }

    /**
     * Get code
     *
     * @return string
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * Set user
     *
     * @param \AppBundle\Entity\User $user
     *
     * @return PromoteExchange
     */
    public function setUser(\AppBundle\Entity\User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \AppBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }




    /**
     * Set promoteSucursal
     *
     * @param \AppBundle\Entity\PromoteSucursal $promoteSucursal
     *
     * @return PromoteExchange
     */
    public function setPromoteSucursal(\AppBundle\Entity\PromoteSucursal $promoteSucursal)
    {
        $this->promote_sucursal = $promoteSucursal;

        return $this;
    }

    /**
     * Get promoteSucursal
     *
     * @return \AppBundle\Entity\PromoteSucursal
     */
    public function getPromoteSucursal()
    {
        return $this->promote_sucursal;
    }
}

¿Alguna idea de cómo resolverlo?

Al generar el Form con el command me genera este form. Pero lo que necesito es que el form me permita elegir dentro de las sucursales que solo se relacionan con promote. Ahi esta mi inconveniente.

PromoteType.php

->add('promoteSucursal', EntityType::class, array(
            'class' => 'AppBundle\Entity\Sucursal',
            'choice_label'=> 'name',
                    'mapped' => false,
            'label'=> 'Sucursales con Stock',
            'multiple'=>true,
            'expanded' => true,
            'attr' => array(
                'type' => 'checkbox',
                'value' => ''
            )
        ))
5
  • 1
    cual es el problema? te da algún error o no se carga el servicio???
    – Jakala
    el 25 jul. 2017 a las 11:20
  • Creando un formtype para Exchange obtengo de promotesucursal todos los datos pero no se como obtener solo los relacionados a esa promote.
    – Nicoo1991
    el 25 jul. 2017 a las 11:23
  • Puedes poner el codigo de lo que llevas hasta ahora? No acabo de entender si te refieres a utilizar el formType o a definir tu propio formType de ese campo. Si es lo ultimo, en gitnacho.github.io/symfony-docs-es/cookbook/form/… nacho explica como hacerlos con eventos. Echale un vistazo
    – Jakala
    el 25 jul. 2017 a las 11:36
  • No se entiende muy bien el problema. Si ya tienes creadas las entidades crea el form de las mismas. Si definiste la base de datos correctamente te realizará esta acción. symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/… el 25 jul. 2017 a las 11:39
  • Reformule la pregunta. Mi entidad PromoteExchange debe guardar promote, sucursal y user. Pero antes está PromoteSucursal que son todas las promote con su sucursal ya seleccionada.
    – Nicoo1991
    el 25 jul. 2017 a las 13:28

1 respuesta 1

0

Creo que lo que buscas es como hacer un formulario con campos dependientes. Tienes un ejemplo en http://showmethecode.es/php/symfony/symfony2-selects-dependientes-mediante-eventos/, Podrias hacer algo como esto:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('code');


    // el siguiente anonym se encarga de añadir el campo promote_sucursal segun datos indicados
    $formModifier = function (FormInterface $form, $code = null) {
        $choices = null === $code ? array() : $form->getData()->get();

        $form
        ->add(
            'promote_sucursal',
            'entity',
            [
                'required' => false,
                'class' => 'AppBundle:PromoteSucursal',
                'choices' => $choices,
            ]
        )
            ;

    };

// añado un evento al crear el formulario, para que añada el campo promote_sucursal vacio
    $builder->addEventListener(
        FormEvents::PRE_SET_DATA,
        function(FormEvent $event) use ($formModifier) {
            $data = $event->getData();
            $code = is_null($data) ? null: $data->getCode();
            $formModifier($event->getForm(), $code);
        }
    );

    //añado el evento despues del submit, para añadir el campo con valores dependientes
    $builder->get('code')->addEventListener(
        FormEvents::POST_SUBMIT,
        Function(FormEvent $event) use ($formModifier) {
            $code = $event->getForm()->getData();

            $formModifier($event->getForm()->getParent(), $code);
        }
    );

Falta añadir el javascript correspondiente para que en el evento change del selector, te envié el formulario y te devuelva otro html. Luego desde ajax, recoges el resultado del campo que ha cambiado y lo sobreescribes en tu html.

fijate en la documentacion, esta muy bien explicado.

1
  • Jakala lo que ncesito es hacer por medio de checkboxes que se puedan seleccionar todas las sucursales en las que esta promote. lo logre con entitytype pero tengo que poner en el form 'mapped' => false y por lo tanto cuando quiero editar un promote no recibe las sucursales ya anteriormente persistidas en promoteSucursal.
    – Nicoo1991
    el 25 ago. 2017 a las 13:16

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.