How to make a component that have an EditForm and encapsulate the form and the validation inside?
Asked Answered
F

1

3

I want to make a component that have a EditForm and encapsulate the form and the validation inside of the component.

And I want to reuse this component anywhere in my application and submit it using any button.

How can I submit a EditForm from a button that is outside of it?

Observation: I have searched for other answers like this one but the answer that is marked as accepted doesn't answer the question and that is why I'm making this new question.

Format answered 18/3, 2020 at 12:55 Comment(11)
IMO having a submit button outside a form is not a good idea...Commencement
Why do you want to create a this reusable component ? It sounds like you are reinventing the EditForm itselfCommencement
Why don't you include the submit button in your component ?Commencement
Why everyone that ask this question, get comments like Why you want to do this? The reason why I want this is so I can edit an entity in multiple places of my app without having to rewrite the form everytime. And I don't want to include the submit button because in some cases the form will appear inside a modal and the submit button of that form will be the modal buttonFormat
Just create the form whitout including the EditForm then. The EditContext is a Cascadind value.Commencement
And set the EditForm at page levelCommencement
@aguafrommars If I do that, I won't be able to encapsulate the OnValidSubmitFormat
Why not ? You OnValidSubmit handler can set a binded parameter of your reusable form component to trigger the submit code. Or you can get a ref of your component a call a method. learn.microsoft.com/en-us/aspnet/core/blazor/…Commencement
Oh, I didn't thought about that. So this is perfect, exactly what I wanted. Could you write that as an answer?Format
yes sure, I do it right nowCommencement
If you just got here, you should take a look at this answerFormat
C
2

Instead of including the EditForm in the component, create a component without the EditForm and call a component's method on OnValidSubmit

<EditForm OnValidSubmit="HandleValidSubmit">
    <FormContentComponent @ref="_formContent" />
    <button type="submit">submit</button>
</EditForm>
@code {
    private FormContentComponent _formContent;

    private void HandleValidSubmit()
    {
        _formContent.HandleValidSubmit();
    }
}
Commencement answered 18/3, 2020 at 13:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.