Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [Symfony][Symfony2] UpdateAction przy uploadzie pliku
Forum PHP.pl > Forum > PHP > Frameworki
mattix19
Witam,

Mam taką oto akcję update do bazy danych:
  1. public function updateAction(Request $request, $id)
  2. {
  3. $em = $this->getDoctrine()->getManager();
  4.  
  5. $entity = $em->getRepository('(...)Bundle:Products')->find($id);
  6.  
  7. if (!$entity) {
  8. throw $this->createNotFoundException('Unable to find Products entity.');
  9. }
  10.  
  11. $editForm = $this->createEditForm($entity);
  12. $editForm->handleRequest($request);
  13.  
  14. if ($editForm->isValid()) {
  15. $file = $editForm->get('photo')->getData();
  16. $name = $file->getClientOriginalName();
  17. $file->move('../web/bundles/static/img/', $name);
  18.  
  19. $product = new Products();
  20. $product->setName( $editForm->get('name'));
  21. $product->setPhoto($name);
  22. $product->setEAN( $editForm->get('eAN'));
  23. $product->setFeatures( $editForm['features']->getData());
  24.  
  25. $em->persist($product);
  26. $em->flush();
  27.  
  28. return $this->redirect($this->generateUrl('admin_produkty_edit', array('id' => $id)));
  29. }
  30.  
  31. return $this->render('(..)Bundle:Products:edit.html.twig', array(
  32. 'entity' => $entity,
  33. 'edit_form' => $editForm->createView(),
  34. ));
  35. }

Problem polega na tym jak wykonać update tej funkcji:
  1. $product->setFeatures();
?
formularz wygląda tak:
  1. private function createEditForm($entity)
  2. {
  3. $form = $this->createFormBuilder($entity)
  4. ->add('name', 'text', array('label' => 'Nazwa'))
  5. ->add('photo', 'file', array('label' => 'Zdjęcie', 'data' => ''))
  6. ->add('eAN', 'text', array('label' => 'Kod EAN'))
  7. ->add('features' , 'entity', array(
  8. 'class' => '(...)Bundle:Features',
  9. 'property' => 'name',
  10. 'multiple' => true,
  11. "expanded" => true,
  12. 'label' => 'Wybierz cechy: ',
  13. ))
  14. ->add('submit', 'submit', array('label' => 'Zapisz zmiany'))
  15. ->getForm();
  16.  
  17. return $form;
  18. }


a akcja dodawania do bazy tak:

  1. public function createAction(Request $request)
  2. {
  3. $form = $this->createCreateForm();
  4. $form->submit($request);
  5. if ($form->isValid()) {
  6. $data = $form->getData();
  7. $name = $data['photo']->getClientOriginalName(); //nazwa pliku
  8. $data['photo']->move('../web/bundles/static/img/', $name);
  9.  
  10. $em = $this->getDoctrine()->getManager();
  11. $product = new Products();
  12. $product->setName($data['name']);
  13. $product->setPhoto($name);
  14. $product->setEAN($data['eAN']);
  15. $product->setFeatures($data['features']);
  16. $em->persist($product);
  17. $em->flush();
  18.  
  19. return $this->redirect($this->generateUrl('produkty'));
  20. }
  21.  
  22. return $this->render('(...)Bundle:Products:new.html.twig', array(
  23. 'form' => $form->createView(),
  24. ));
  25. }

w przypadku dodawania do bazy wszystko działa wystarczy że wrzuciłem tablicę do funckji setFeatures() natomiast jak wykonuję update to ta funkcja nie działa. Jak wykonać update do bazy która ma relację m:n i jednocześnie wykonać upload pliku?
pozdrawiam
cadavre
Założę się, że jeśli przeglądniesz DQLe które wykonywane są w updateAction - znajdziesz tam UPDATE'a Twojej encji Products, ale nie update'a zależniej od niego encji Features.

Pokaż encję Products, oczywiście tylko ogólne elementy i te które zależą od Features. smile.gif
mattix19
Oto encje. Zrobiłem je poprawnie bo gdyby nie upload pliku to działałoby to idealnie. Ja mam bardziej kłopot z tym jak z tego requesta wyciągnąć całą tablicę dla features żeby upload zadziałał. W przypadku dodawania do bazy to działa przy update już nie.
  1. /**
  2.  * Features
  3.  *
  4.  * @ORM\Table()
  5.  * @ORM\Entity
  6.  */
  7. class Features
  8. {
  9. /**
  10.   * @var integer
  11.   *
  12.   * @ORM\Column(name="id", type="integer")
  13.   * @ORM\Id
  14.   * @ORM\GeneratedValue(strategy="AUTO")
  15.   */
  16. private $id;
  17.  
  18. /**
  19.   * @var string
  20.   *
  21.   * @ORM\Column(name="name", type="string", length=255)
  22.   */
  23. private $name;
  24.  
  25. /**
  26.   * @var string
  27.   *
  28.   * @ORM\Column(name="value", type="string", length=255)
  29.   */
  30. private $value;
  31.  
  32. /**
  33.   * @ORM\ManyToMany(targetEntity="Products", mappedBy="features", cascade={"remove"})
  34.   */
  35. private $products;
  36. }
  37.  
  38. class Products
  39. {
  40. /**
  41.   * @var integer
  42.   *
  43.   * @ORM\Column(name="id", type="integer")
  44.   * @ORM\Id
  45.   * @ORM\GeneratedValue(strategy="AUTO")
  46.   */
  47. private $id;
  48. (..)
  49.  
  50. /**
  51.   * @var string
  52.   *
  53.   * @ORM\Column(name="photo", type="string", length=255)
  54.   */
  55. private $photo;
  56.  
  57. (..)
  58.  
  59. /**
  60.   * @ORM\ManyToMany(targetEntity="Features", inversedBy="products")
  61.   * @ORM\JoinTable(name="product_has_feature")
  62.   */
  63. private $features;
  64. }
semafor1985
jak nie wiedziałem jak uploadować plik, korzystałem z tego:

http://symfony2.ylly.fr/upload-file-with-d...ny2-jordscream/

sprawdzone, działa
punkomuzykant
Nie wnikałem w temat zbyt długo ale pewnie chodzi o listener ?
http://symfony.com/doc/current/cookbook/do...ubscribers.html

Dodajesz w config coś jak w linku + jeśli chcesz mieć container dajesz arguments: ['@service_container'] żeby go przekazać do konstruktora

Kod
services:
    Twoj.listener:
        class: moja\klasa
        arguments: ['@service_container']
        tags:
            - { name: doctrine.event_listener, event: preUpdate }
            - { name: doctrine.event_listener, event: prePersist }


i potem np

Kod
namespace twoje dane;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;

class TwojListener {

    protected $container;

    public function __construct(ContainerInterface $container) {
        $this->container = $container;
    }

    public function prePersist(LifecycleEventArgs $args) {

        $entity = $args->getEntity();

        
    }

    public function preUpdate(LifecycleEventArgs $args) {

        $entity = $args->getEntity();

      
    }

}


W ten sposób tworzysz nasłuch na encje a jeśli interesuje Ciebie jakaś konkretna to możesz strzelić np
if ($entity instanceof MojaKlasa) {

w preUpdate czy persist

To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.