0

I’ve encountered this issue several time and I don’t know why. I know this not so easy to reproduce but maybe someone has an explanation.

I’ve built several custom modules which return datas from Rest APIs (I use controller, not Form). These modules are in custom block (define in src/Plugin/Block/HelloBlock.php) They all work well.

When I made a custom module with Form API that allow user to select a range of date and return a pdf file, I had a weird bug : pdf file is downloaded but it is always empty (0 ko).

If I display the form with a route (defined in module.routing.yml), then it works.

Do you know why Form Api behaves differently in route and in custom block ?

Code for block:

class WebservicesTestBlock extends BlockBase {

    public function build() {

        $form = \Drupal::formBuilder()->getForm('Drupal\webservices_test\Form\WebservicesTestForm');
        return $form;

    }

}

And in form :

public function submitForm(array &$form, FormStateInterface $form_state) {


        // here is the code that returns pdf datas from rest api
        // I've omitted this part because it is working
        // The PDF datas is in $test->body

        header("Content-Type: application/pdf");
        header("Content-Disposition: attachment; filename=test.pdf");
        header('Content-Transfer-Encoding: binary');
        //header("Cache-Control", "max-age=0");
        header('Accept-Ranges: bytes');
        ob_clean();
        flush();
        echo ($test->body);
        exit;

    }
  • 2
    The form submit should return a BinaryFileResponse if you want to issue an immediate download. Also hard to tell from this code but it’s possible your file path for the pdf is incorrect? – Kevin Jun 25 at 11:18
  • 1
    You shouldn't use low level output functions like echo or header in D8. This results in erratic behavior impossible to debug. – 4k4 Jun 25 at 12:53
  • 1
    As @Kevin pointed out return a response in $form_state->setResponse($response) – 4k4 Jun 25 at 13:00
  • 1
    see drupal.stackexchange.com/a/263660/47547 – 4k4 Jun 25 at 13:07
  • 2
    Possible duplicate of Why isn't this functionality in submitForm firing? – leymannx Jun 25 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.