简体   繁体   中英

How to send a form on a distant API using symfony2 forms

I made a bundle in my symfony2 project to handle all the webservices I use to save my files in the cloud (like amazon S3). Some of this webservices allow to send files directly on their Server without using mine with forms like that :

<form action="api.thecloud.com/specificId?redirectUrl=MyUrlToGetTheResponse" >
    <input type="file" name="file" />
    <input type="submit" />
</form>

The given redirectUrl param allow me to get informations from the upload and save its in my database.

My problem is that I want to make it transparent and customizable for the other bundles, like with a standart symfony form type. Is there a good way to do this ?

The solution I found is a bit complex and I think there is a cleaner way to do this :

I create a form type which specify the action url :

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('file', 'file');
    $builder->add('otherPostUploadInformation', 'hidden');
    $builder->setAction( $this->Cloudservice->generateUploadUrl( 'my_redirect_url' ) ) ;
}
public function getName(){
    return '';
}

The action route is given in an other way (php or twig function) and saved in a session.

In my_redirect_url's action, I get and save the informations from the webservice and redirect to the action saved in session :

    public function myRedirectUrlAction() {

        $request = $this->getRequest() ;

        // Recreate a form with received information
        $rsrc = new CloudUploadRessource( $request->query->get( 'id' ), $request->query->get( 'url' ) );
        $form = $this->createForm(new CloudUploadType(), $rsrc );

        // transform it to array and add it to the request like if it has been posted
        $formArray = $this->transformFormArray( $form->createView() ) ;
        $request->request->add( $formArray);

        // redirect to the client action url with the request
        // So he can do $form->bind($request); $form->isValid(); ... 
        $clientActionRoute = $request->getSession()->get( 'clientActionRoute' ) ;
        return $this->forward($clientActionRoute, array('request' => $request ) );
    }

Thanks

As for me, it is kind a strangely to use such methods (uploading files directly to third party resource). Why don't you just use bundle like : https://github.com/KnpLabs/KnpGaufretteBundle . You may configure as many adapters as you need. But in this case, you'll be able to test your entire application/project by just changing the addapters configuration for test/dev env.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM