4

I have a form in my Symfony2 app where I ask a user to upload a file. This field is not required. Currently I process the user`s file with the following command:

$file = $form['attachement']->getData();

My question is how can I set a default file in case $file returns NULL, i.e. the user does not want to upload any file? Thank you.

2 Answers 2

1

First, you have to create a valid object from your default file.
To do that, use the Symfony\Component\HttpFoundation\File.

Usage: $file = new File('path/of/your/default/file');

Then, you have to update your form before the data binding is done.
For that, you have two solutions :

1- Use a FormEvent to manually set the file if the field is null. (e.g. PRE_SUBMIT and POST_SUBMIT)

2- Use a prePersist/preUpdate hook in your entity. (Doesn't involves to move your logic, the unmapped property 'attachment' should already exists in your entity)

For the option 1, see the Dynamic form modification chapter of the cookbook and look for the appropriated event (the documentation will give the informations to choose it).

For the 2, see the Events chapterof Doctrine documentation.
Something like the following should do the job :

/**
 * @ORM\HasLifecycleCallbacks
 */
class YourEntity {
    /**
     *
     * @ORM\PrePersist
     * @ORM\PreUpdate
     */
    public function manageFile()
    {
        if ($this->attachment === null) {
            $file = new File('path/of/your/default/file');
            $this->setAttachment($file);
        }
    }
}

I hope it's sufficient for you.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You. Actually $file = new File('path/of/your/default/file'); was enough to do all the stuff))
0

I guess, doctrine Lifecycle Events should help you. Use prePersist or preUpdate event to check is $this->file === null, and set default value.

3 Comments

Currently I check if the file!=null in my controller. The problem is that I want to set a default file in else statement but I can`t find a function for that. If I use setFile("file/path") I get Call to a member function setFile() on null.
@Jack, you can move this logic from controller to entity. It allows you to set default value in time, when entity created. Is that what you want?
Actually I would like to leave it in a controller as it is now. But if there is no way for that, I would move it to entity. I`ve read the docs about Lifecycle callbacks but did not find any info on how to set a default file either((.Maybe somebody could point on it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.