Search code examples
formstypo3fluidextbase

Dynamic recipient in form


I have a custom extension with list and detail of teachers. On the detail page I include a form with code:

<formvh:render persistenceIdentifier="1:/form_definitions/myform.yaml" />

I need to set the recipient with the teacher's email shown on the page. How can I do?


Solution

  • You can achieve that by writing a custom form finisher.

    • Add a hidden field to your form which holds the the ID of the teacher
    • Fetch that id in your form finisher and load the Teacher model by your repository

    A (not complete) example of a form finisher, which loads recipient data from a custom model and sends the mail to this specific data:

    class EmailToContactPersonFinisher extends EmailFinisher
    {
    /**
     * Executes this finisher
     * @see AbstractFinisher::execute()
     *
     * @throws FinisherException
     */
    protected function executeInternal()
    {
        /** @var FormRuntime $formRuntime */
        $formRuntime = $this->finisherContext->getFormRuntime();
        if ($formRuntime->getResponse()->getRequest()) {
            if ($formRuntime->getResponse()->getRequest()->hasArgument('contactPerson')) {
                $objectManager = GeneralUtility::makeInstance(ObjectManager::class);
                /** @var ContactPersonRepository $repository */
                $contactPersonRepository = $objectManager->get(ContactPersonRepository::class);
                /** @var ContactPerson $contactPerson */
                $contactPerson = $contactPersonRepository->findByUid($formRuntime->getResponse()->getRequest()->getArgument('contactPerson'));
            }
        }
        // override contactPerson related options
        if ($contactPerson instanceof ContactPerson) {
            if ($contactPerson->getEmail()) {
                $recipientAddress = $contactPerson->getEmail();
            }
        }
        $this->setOption('recipientAddress', $recipientAddress);
        parent::executeInternal();
    }
    }
    

    You can also have a look at the standard emailFinisher, which gives you quick idea on the architecture. sysext/form/Classes/Domain/Finishers/EmailFinisher.php