Skip to content

[Live] Re-extracting form data after submit #254

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/LiveComponent/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
- Added `data-live-ignore` attribute. If included in an element, that element
will not be updated on re-render.

- `ComponentWithFormTrait` no longer has a `setForm()` method. But there
is also no need to call it anymore. To pass an already-built form to
your component, pass it as a `form` var to `component()`. If you have
a custom `mount()`, you no longer need to call `setForm()` or anything else.

- The Live Component AJAX endpoints now return HTML in all situations
instead of JSON.

Expand Down
1 change: 1 addition & 0 deletions src/LiveComponent/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"doctrine/doctrine-bundle": "^2.0",
"doctrine/orm": "^2.7",
"symfony/dependency-injection": "^5.4|^6.0",
"symfony/form": "^5.4|^6.0",
"symfony/framework-bundle": "^5.4|^6.0",
"symfony/phpunit-bridge": "^6.0",
"symfony/security-csrf": "^5.4|^6.0",
Expand Down
76 changes: 44 additions & 32 deletions src/LiveComponent/src/ComponentWithFormTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Symfony\UX\LiveComponent\Attribute\BeforeReRender;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\Util\LiveFormUtility;
use Symfony\UX\TwigComponent\Attribute\PostMount;

/**
* @author Ryan Weaver <[email protected]>
Expand Down Expand Up @@ -63,17 +65,29 @@ trait ComponentWithFormTrait
*/
abstract protected function instantiateForm(): FormInterface;

/**
* Override in your class if you need extra mounted values.
*
* Call $this->setForm($form) manually in that situation
* if you're passing in an initial form.
*/
public function mount(?FormView $form = null)
#[PostMount]
public function postMount(array $data): array
{
if ($form) {
$this->setForm($form);
// allow the FormView object to be passed into the component() as "form"
if (\array_key_exists('form', $data)) {
$this->formView = $data['form'];
unset($data['form']);

if ($this->formView) {
// if a FormView is passed in and it contains any errors, then
// we mark that this entire component has been validated so that
// all validation errors continue showing on re-render
if (LiveFormUtility::doesFormContainAnyErrors($this->formView)) {
$this->isValidated = true;
$this->validatedFields = [];
}
}
}

// set the formValues from the initial form view's data
$this->initializeFormValues();

return $data;
}

/**
Expand All @@ -87,7 +101,7 @@ public function mount(?FormView $form = null)
public function submitFormOnRender(): void
{
if (!$this->getFormInstance()->isSubmitted()) {
$this->submitForm(false);
$this->submitForm($this->isValidated);
}
}

Expand All @@ -103,18 +117,6 @@ public function getForm(): FormView
return $this->formView;
}

/**
* Call this from mount() if your component receives a FormView.
*
* If your are not passing a FormView into your component, you
* don't need to call this directly: the form will be set for
* you from your instantiateForm() method.
*/
public function setForm(FormView $form): void
{
$this->formView = $form;
}

public function getFormName(): string
{
if (!$this->formName) {
Expand All @@ -124,18 +126,19 @@ public function getFormName(): string
return $this->formName;
}

public function getFormValues(): array
private function initializeFormValues(): void
{
if (null === $this->formValues) {
$this->formValues = $this->extractFormValues($this->getForm());
}

return $this->formValues;
$this->formValues = $this->extractFormValues($this->getForm());
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Everything above this was just cleaning up the flow, but not significant


private function submitForm(bool $validateAll = true): void
{
$this->getFormInstance()->submit($this->formValues);
if (null !== $this->formView) {
throw new \LogicException('The submitForm() method is being called, but the FormView has already been built. Are you calling $this->getForm() - which creates the FormView - before submitting the form?');
}

$form = $this->getFormInstance();
$form->submit($this->formValues);

if ($validateAll) {
// mark the entire component as validated
Expand All @@ -146,10 +149,19 @@ private function submitForm(bool $validateAll = true): void
// we only want to validate fields in validatedFields
// but really, everything is validated at this point, which
// means we need to clear validation on non-matching fields
$this->clearErrorsForNonValidatedFields($this->getFormInstance(), $this->getFormName());
$this->clearErrorsForNonValidatedFields($form, $form->getName());
}

if (!$this->getFormInstance()->isValid()) {
// re-extract the "view" values in case the submitted data
// changed the underlying data or structure of the form
$this->formValues = $this->extractFormValues($this->getForm());
// remove any validatedFields that do not exist in data anymore
$this->validatedFields = LiveFormUtility::removePathsNotInData(
$this->validatedFields ?? [],
[$form->getName() => $this->formValues],
);

if (!$form->isValid()) {
throw new UnprocessableEntityHttpException('Form validation failed in component');
}
}
Expand Down Expand Up @@ -192,7 +204,7 @@ private function getFormInstance(): FormInterface
return $this->formInstance;
}

private function clearErrorsForNonValidatedFields(Form $form, $currentPath = ''): void
private function clearErrorsForNonValidatedFields(Form $form, string $currentPath = ''): void
{
if (!$currentPath || !\in_array($currentPath, $this->validatedFields, true)) {
$form->clearErrors();
Expand Down
Loading