Foros del Web » Programando para Internet » PHP » Frameworks y PHP orientado a objetos »

Doctrine ORM + FormBuilder en Silex para crear un formulario

Estas en el tema de Doctrine ORM + FormBuilder en Silex para crear un formulario en el foro de Frameworks y PHP orientado a objetos en Foros del Web. Estimados, estoy hace un tiempo con Silex, y bueno ahora he agregado Doctrine ORM por medio de dflydev https://github.com/dflydev/dflydev-d...rvice-provider todo funciona bien, pero lo que ...
  #1 (permalink)  
Antiguo 02/06/2013, 20:28
Avatar de xalupeao  
Fecha de Ingreso: mayo-2008
Ubicación: Santiago, Chile
Mensajes: 749
Antigüedad: 15 años, 11 meses
Puntos: 12
Doctrine ORM + FormBuilder en Silex para crear un formulario

Estimados,

estoy hace un tiempo con Silex, y bueno ahora he agregado Doctrine ORM por medio de dflydev

https://github.com/dflydev/dflydev-d...rvice-provider

todo funciona bien, pero lo que no he podido hacer funcionar es que el FormBuilder detecte las relaciones (Many To One, One To Many, etc) y las muestre en el formulario.

Lo que necesito es que el formulario me muestre el listado de empresas al momento de agregar un contacto.

Lo que tengo en el controllers.php

Código PHP:
Ver original
  1. $app->match('/add-contact', function(Request $request) use ($app) {
  2.  
  3.     $form = $app['form.factory']->create(new ContactType());
  4.  
  5.     if('POST' == $request->getMethod()) {
  6.         $form->bind($request);
  7.  
  8.         if($form->isValid()) {
  9.             $data = $form->getData();
  10.             $app['db']->insert('contacts', $data);
  11.  
  12.             $app['session']->getFlashBag()->add('success', 'Haz añadido un contacto. Amalo! :)');
  13.  
  14.             return $app->redirect($app['url_generator']->generate('add-contact'));
  15.         }
  16.     }
  17.     return $app['twig']->render('backend/add-contact.html.twig', array('form' => $form->createView()));
  18. })
  19. ->bind('add-contact')
  20. ->method('GET|POST')
  21. ;

y en ContactType tengo lo siguiente:

Código PHP:
Ver original
  1. <?php
  2.  
  3. namespace App\Form;
  4.  
  5. use Symfony\Component\Form\AbstractType;
  6. use Symfony\Component\Form\FormBuilderInterface;
  7. use Symfony\Component\OptionsResolver\OptionsResolverInterface;
  8. use Symfony\Component\Validator\Constraints as Assert;
  9.  
  10. class ContactType extends AbstractType
  11. {
  12.     public function buildForm(FormBuilderInterface $builder, array $options)
  13.     {
  14.         $builder
  15.             ->add('name')
  16.             ->add('phone')
  17.             ->add('email')
  18.             ->add('company')
  19.         ;
  20.  
  21.     }
  22.  
  23.     public function setDefaultOptions(OptionsResolverInterface $resolver)
  24.     {
  25.         $resolver->setDefaults(array(
  26.             'data_class' => 'Entity\Contact'
  27.         ));
  28.     }
  29.  
  30.     public function getName()
  31.     {
  32.         return 'contact';
  33.     }
  34. }

y el la Entidad Contact, tengo lo siguiente:

Código PHP:
Ver original
  1. <?php
  2.  
  3. namespace Entity;
  4.  
  5. use Doctrine\ORM\Mapping as ORM;
  6.  
  7. /**
  8.  * Contact
  9.  *
  10.  * @ORM\Table(name="contacts")
  11.  * @ORM\Entity
  12.  */
  13. class Contact
  14. {
  15.     /**
  16.      * @var integer
  17.      *
  18.      * @ORM\Column(name="id", type="integer", precision=0, scale=0, nullable=false, unique=false)
  19.      * @ORM\Id
  20.      * @ORM\GeneratedValue(strategy="IDENTITY")
  21.      */
  22.     private $id;
  23.  
  24.     /**
  25.      * @var string
  26.      *
  27.      * @ORM\Column(name="name", type="string", length=45, precision=0, scale=0, nullable=false, unique=false)
  28.      */
  29.     private $name;
  30.  
  31.     /**
  32.      * @var string
  33.      *
  34.      * @ORM\Column(name="phone", type="string", length=20, precision=0, scale=0, nullable=false, unique=false)
  35.      */
  36.     private $phone;
  37.  
  38.     /**
  39.      * @var string
  40.      *
  41.      * @ORM\Column(name="email", type="string", length=150, precision=0, scale=0, nullable=false, unique=false)
  42.      */
  43.     private $email;
  44.  
  45.     /**
  46.      * @var \Doctrine\Common\Collections\Collection
  47.      *
  48.      * @ORM\OneToMany(targetEntity="Entity\Job", mappedBy="contact")
  49.      */
  50.     private $jobs;
  51.  
  52.     /**
  53.      * @var \Entity\Company
  54.      *
  55.      * @ORM\ManyToOne(targetEntity="Entity\Company", inversedBy="contact", cascade={"remove"})
  56.      * @ORM\JoinColumns({
  57.      *   @ORM\JoinColumn(name="company_id", referencedColumnName="id", nullable=true)
  58.      * })
  59.      */
  60.     private $company;
  61.  
  62.     /**
  63.      * Constructor
  64.      */
  65.     public function __construct()
  66.     {
  67.         $this->jobs = new \Doctrine\Common\Collections\ArrayCollection();
  68.     }
  69.  
  70.     /**
  71.      * Get id
  72.      *
  73.      * @return integer
  74.      */
  75.     public function getId()
  76.     {
  77.         return $this->id;
  78.     }
  79.  
  80.     /**
  81.      * Set name
  82.      *
  83.      * @param string $name
  84.      * @return Contact
  85.      */
  86.     public function setName($name)
  87.     {
  88.         $this->name = $name;
  89.  
  90.         return $this;
  91.     }
  92.  
  93.     /**
  94.      * Get name
  95.      *
  96.      * @return string
  97.      */
  98.     public function getName()
  99.     {
  100.         return $this->name;
  101.     }
  102.  
  103.     /**
  104.      * Set phone
  105.      *
  106.      * @param string $phone
  107.      * @return Contact
  108.      */
  109.     public function setPhone($phone)
  110.     {
  111.         $this->phone = $phone;
  112.  
  113.         return $this;
  114.     }
  115.  
  116.     /**
  117.      * Get phone
  118.      *
  119.      * @return string
  120.      */
  121.     public function getPhone()
  122.     {
  123.         return $this->phone;
  124.     }
  125.  
  126.     /**
  127.      * Set email
  128.      *
  129.      * @param string $email
  130.      * @return Contact
  131.      */
  132.     public function setEmail($email)
  133.     {
  134.         $this->email = $email;
  135.  
  136.         return $this;
  137.     }
  138.  
  139.     /**
  140.      * Get email
  141.      *
  142.      * @return string
  143.      */
  144.     public function getEmail()
  145.     {
  146.         return $this->email;
  147.     }
  148.  
  149.     /**
  150.      * Add jobs
  151.      *
  152.      * @param \Entity\Job $jobs
  153.      * @return Contact
  154.      */
  155.     public function addJob(\Entity\Job $jobs)
  156.     {
  157.         $this->jobs[] = $jobs;
  158.  
  159.         return $this;
  160.     }
  161.  
  162.     /**
  163.      * Remove jobs
  164.      *
  165.      * @param \Entity\Job $jobs
  166.      */
  167.     public function removeJob(\Entity\Job $jobs)
  168.     {
  169.         $this->jobs->removeElement($jobs);
  170.     }
  171.  
  172.     /**
  173.      * Get jobs
  174.      *
  175.      * @return \Doctrine\Common\Collections\Collection
  176.      */
  177.     public function getJobs()
  178.     {
  179.         return $this->jobs;
  180.     }
  181.  
  182.     /**
  183.      * Set company
  184.      *
  185.      * @param \Entity\Company $company
  186.      * @return Contact
  187.      */
  188.     public function setCompany(\Entity\Company $company = null)
  189.     {
  190.         $this->company = $company;
  191.  
  192.         return $this;
  193.     }
  194.  
  195.     /**
  196.      * Get company
  197.      *
  198.      * @return \Entity\Company
  199.      */
  200.     public function getCompany()
  201.     {
  202.         return $this->company;
  203.     }
  204.  
  205.     public function __toString()
  206.     {
  207.         return $this->name;
  208.     }
  209. }

Con todo este codigo no obtengo un Select en la vista... como deberia pasar.




espero que me puedan ayudar.

Gracias :)
__________________
Hosting en Chile en Silverhost - La solución en Hosting en Chile.
  #2 (permalink)  
Antiguo 06/06/2013, 12:29
Avatar de repara2  
Fecha de Ingreso: septiembre-2010
Ubicación: München
Mensajes: 2.445
Antigüedad: 13 años, 6 meses
Puntos: 331
Respuesta: Doctrine ORM + FormBuilder en Silex para crear un formulario

Consulta un foro doctrine.
__________________
Fere libenter homines, id quod volunt, credunt.
  #3 (permalink)  
Antiguo 19/03/2014, 20:40
 
Fecha de Ingreso: junio-2003
Ubicación: Carlos Paz - Cordoba
Mensajes: 91
Antigüedad: 20 años, 9 meses
Puntos: 0
Respuesta: Doctrine ORM + FormBuilder en Silex para crear un formulario

hola, estoy renegando con lo mismo, pudiste resolver esto?
saludos!
__________________
Daniel Schell
Promoviendo el Desarrollo Humano
www.elsenderodelmedio.com.ar
  #4 (permalink)  
Antiguo 20/03/2014, 06:31
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Doctrine ORM + FormBuilder en Silex para crear un formulario

Podrías utilizar el type entity http://symfony.com/doc/current/refer...es/entity.html

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #5 (permalink)  
Antiguo 20/03/2014, 06:51
 
Fecha de Ingreso: junio-2003
Ubicación: Carlos Paz - Cordoba
Mensajes: 91
Antigüedad: 20 años, 9 meses
Puntos: 0
Respuesta: Doctrine ORM + FormBuilder en Silex para crear un formulario

Sí, esa es la idea, pero estoy con Silex y por lo que veo es dificil registrar/instalar Doctrine ORM en Silex. Cansado de intentar, voy a hacerlo con Symfony.
Gracias!
__________________
Daniel Schell
Promoviendo el Desarrollo Humano
www.elsenderodelmedio.com.ar
  #6 (permalink)  
Antiguo 20/03/2014, 07:05
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Doctrine ORM + FormBuilder en Silex para crear un formulario

Verdad, es parte del bridge, de todas formas, este provider no sirve https://github.com/dflydev/dflydev-d...rvice-provider, porque bastaria con inyectar el repositorio en el form y crear los choices en el build.

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #7 (permalink)  
Antiguo 20/03/2014, 07:17
 
Fecha de Ingreso: junio-2003
Ubicación: Carlos Paz - Cordoba
Mensajes: 91
Antigüedad: 20 años, 9 meses
Puntos: 0
Respuesta: Doctrine ORM + FormBuilder en Silex para crear un formulario

"bastaria con inyectar el repositorio en el form y crear los choices en el build." ... justamente .... tampoco pude implementar eso.

// primero, cargo coleccion de categorias
$cat = $app['repository.category']->findAll(200);



// luego intento pasar esas categorias al form y me dice que la variable 'cat' no existe

$form = $app['form.factory']->create(new VehicleType(), $vehicle, array(
'cat' => $cat,
));


Para estar en sintonia, lo hago con Symfony y ya?

Saludos
__________________
Daniel Schell
Promoviendo el Desarrollo Humano
www.elsenderodelmedio.com.ar
  #8 (permalink)  
Antiguo 20/03/2014, 07:35
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Doctrine ORM + FormBuilder en Silex para crear un formulario

En tu lugar le buscaría la vuelta, para mi seria algo asi:

Código PHP:
Ver original
  1. class VehicleType
  2. {
  3.     public function __construct(RepositoryInterface $repository)
  4.     {
  5.         $this->repository = $repository;
  6.     }
  7.  
  8.     public function buildForm(FormBuilderInterface $builder, array $options)
  9.     {      
  10.         $builder            
  11.             ->add('entities', array(), array('choices' => $this->repository->findAll()))
  12.         ;
  13.  
  14.     }  
  15. }
  16.  
  17. new VehicleType($app['repository']);
__________________
http://es.phptherightway.com/
thats us riders :)
  #9 (permalink)  
Antiguo 20/03/2014, 08:29
 
Fecha de Ingreso: junio-2003
Ubicación: Carlos Paz - Cordoba
Mensajes: 91
Antigüedad: 20 años, 9 meses
Puntos: 0
Respuesta: Doctrine ORM + FormBuilder en Silex para crear un formulario

no lo vas a creer, anduvo this facking shit!!!

gracias brother!!


--aqui el codigo---


MasEventos\Form\Type\VehicleType.php
------------------------------------

class VehicleType extends AbstractType

protected $_repository;

public function __construct($repository)
{
$this->_repository = $repository;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
$cat = $this->_repository->findAll(200);

$builder->add('category','choice', array(
'choices' => $cat,
'required' => false));


src\MasEventos\Controller\VehicleController.php
-------------------------------------------------

class VehicleController

public function addAction(Request $request, Application $app)

$vehicle = new Vehicle();

$form = $app['form.factory']->create(new VehicleType($app['repository.category']), $vehicle);
__________________
Daniel Schell
Promoviendo el Desarrollo Humano
www.elsenderodelmedio.com.ar

Etiquetas: doctrine, formulario, html, orm, php, select
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 02:47.