Rendering a HL7 FHIR Questionnaire component isn't as simple as creating a normal HTML form as each Item component can both be a parent element or a child element.
- See it in action in our FhirBlaze repo
Item can be of type: String, Textarea, Choice, Boolean, Date... etc.... These are easy enough. But an Item can also be a type of Group, which can have the usual types mentioned before AND zero or more Group types.
This makes the rendering of Questionnaire's json object a little bit tricky.
RenderFragments
It's a concept of Templated Controls. Using RenderFragments you can componentize specific portion of HTML. A RenderFragment represents a chunk of Razor markup that can then be rendered by the component
Recursion to save the day
What we've come up with combines RenderFragments and recursion to traverse the nested, tree-structure until it finds an item type that is not of type Group. Then we'll use the recursive function to append to our RenderFragment along the way.
On the front end:
HTML/Blazor Front end
<EditForm Model=@QResponse OnSubmit=@SubmitQuestionnaireAsync>
@DynamicFragment
.
.
</EditForm>
// Frontend @code block
private RenderFragment DynamicFragment;
private void RenderComponent(List<ItemComponent> items)
{
DynamicFragment += GetChildItems(items);
}
private RenderFragment GetChildItems(List<ItemComponent> items) => __builder =>
{
@foreach (var item in items)
{
@if (item.Item.Count > 0)
{
@GetTitle(item.Text);
@GetChildItems(item.Item);
}
else
{
@GetAnswerDisplay(item);
}
<br/>
}
};
We have a DynamicFragment inside the EditForm element. That is a RenderFragment that we'll be using to build the form.
We have two key functions: RenderComponent and GetChildItems. First function updates the RenderFragments with html elements spewed by the second funtion.
Second function is the recursive function that goes through all the Questionnaire items and determines whether it should render an HTML element. If it finds the Item contains another Item with a count greater than 0 we know the type is of 'Group'. The recursion starts again.
Blazor is ultimately going to express that Razor code as a RenderTreeBuilder.
How do you kick off the render?
On the code behind:
protected override async Task OnInitializedAsync()
{
try
{
RenderComponent(QResponse.Item);
.
.
}
During initialization you can simply call the function RenderComponent with all the Questionnaire items!
And here is how it renders.
We hope this helps you as you try to tackle the complexity of Questionnaire component of FHIR.
Posted at https://sl.advdat.com/3Hu6XmN