0

So, as per the docs, this is how we upload a file in Symfony Live components. If we have to upload a file along with other input, how to do it?

Code from docs:

<p>
    <input type="file" name="my_file" />
    <button data-action="live#action" data-live-action-param="files|myAction" />
</p>

Example: I was able to do with

data-live-action-param="files|myAction"

Twig Component:

<div class="col">
      {{ form_row(form.dialogues.album.album_id,{'attr':{'id' : 'album-id'}}) }}
      {{ form_row(form.dialogues.images.image) }}
</div>

LiveComponent

    $imageFile = $request->files->get('exam')['dialogues']['images']['image'];
    $albumId = $request->request->get('exam')['dialogues']['album']['album_id'];

No doubt, $imageFile has no issue, but dd($albumId) says null. How to do this?

1 Answer 1

0

It's hard to answer your question without seeing the full code of the UX Live Component, just to illustrate how I use it (regular form submission + file):

<?php

final class UXLiveComponentExample extends AbstractController
{
    use DefaultActionTrait;
    use ComponentWithFormTrait;
    use ComponentToolsTrait;

    #[LiveProp]
    public ?OtherData $otherData = null;

    #[LiveProp(writable: true)]
    public ?string $screenshot = null;

    protected function instantiateForm(): FormInterface
    {
        return $this->createForm(TheFormType::class, $this->otherData);
    }

    #[LiveAction]
    public function upload(Request $request): void
    {
        $file = $request->files->get('block_screenshot');
// Do what you want with the file.
    }

    #[LiveAction]
    public function save(
        EntityManagerInterface $entityManager,
    ): void
    {
        $this->submitForm();
        $form = $this->getForm();

        /** @var OtherData $otherData */
        $otherData = $form->getData();

        // Only update the screenshot if a new one was uploaded
        if ($this->screenshot && $this->screenshot !== $otherData->getScreenshot()) {
            $otherData->setScreenshot($this->screenshot);
        }

        $entityManager->persist($otherData);
        $entityManager->flush();

        // Done.
    }
}

And the Twig side of things:

<div{{ attributes }}>
    {{ form_start(form) }}
        <label for="block_screenshot">Upload Screenshot</label>
        <input name="block_screenshot" id="block_screenshot_id" type="file">
        <button type="button" data-action="live#action" data-live-action-param="files|upload">Upload screenshot</button>

        {{ form_rest(form) }} <!-- This is where all other form fields are rendered. -->
    {{ form_end(form) }}
</div>

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

Comments

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.