rayfranco rayfranco - 3 months ago 12
PHP Question

Can't upload files with CraueFormFlowBundle

I am trying to upload a file in a multi-step form with CraueFormFlowBundle.

Everything is working fine, but at the end of the process, my entity never get updated with file path as it used to work before

Here is basically what I am trying to do :

// FormType

public function buildForm(FormBuilder $builder, array $options) {
switch ($options['flowStep']) {
case 1:
$builder->add('username', 'text', array('label'=>'Votre pseudo','required'=>false))
->add('file','file', array('label'=>'Photo de profil','required'=>false));
break;
// ....


While my entity is set up like this :

/**
* Ray\CentralBundle\Entity\Client
*
* @ORM\Table(name="clients")
* @ORM\Entity(repositoryClass="Ray\CentralBundle\Entity\ClientRepository")
* @ORM\HasLifecycleCallbacks
*/
class Client implements UserInterface
{
private $filenameForRemove;

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

/**
* @var file $file
*
* @Assert\File(maxSize="6000000")
*/
public $file;

// ...


It seems that when
$flow->saveCurrentStepData();
is called,
$form['file']
is filled and point to the temp file.

What I don't get, is why on the next step, the file value won't get stored in the session.

I've extended the
getSessionData()
method of
Craue\FormFlowBundle\Form\FormFlow
like this :

protected function getSessionData() {

var_dump($this->session->get($this->sessionDataKey, array()));

return $this->session->get($this->sessionDataKey, array());
}


This is giving me all the form data except the "file" one, as expected...

How to get file upload to works with this bundle ?

Answer

this is because you cant store files in the session...

here a possibility to manage it..

Controller

// ...
if ($flow->isValid($form)) {
    $data = $request->request->get($form->getName(), array());

    // upload the entity (Event) main picture
    if ($event->preUpload() && $picture = $event->upload()) {
        $data['picture'] = $picture;
    }


    // save form progress
    $flow->saveCurrentStepData($data);
// ...

Entity Event

// ...

public function preUpload()
{
    if(null !== $this->picturefile)
    {
        $this->picture = uniqid() . '.' . $this->picturefile->guessExtension();
        return $this->picture;
    }
}

And you have to overwrite the FormFlow method saveCurrentStepData() ... (with a custom Bundle with getParent)

public function saveCurrentStepData($data = false) {
    $sessionData = $this->getSessionData();
    $sessionData[$this->currentStep] = $data ? $data : $this->request->request->get($this->formType->getName(), array()) ;
    $this->setSessionData($sessionData);
}