Skip to content

Commit 52e71a8

Browse files
991223: Blazor Documentation cleanup
1 parent 1fe07b5 commit 52e71a8

File tree

1 file changed

+168
-11
lines changed

1 file changed

+168
-11
lines changed

blazor/rich-text-editor/mail-merge.md

Lines changed: 168 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,184 @@ control: RichTextEditor
77
documentation: ug
88
---
99

10-
# Mail merge in Blazor Rich Text Editor Control
10+
# Mail Merge in Syncfusion Blazor RichTextEditor
1111

12-
The **Mail Merge** feature in Syncfusion Blazor Rich Text Editor enables you to create dynamic, personalized documents by inserting placeholders (merge fields) into the editor content. These placeholders are later replaced with actual data at runtime, making it ideal for generating letters, invoices, and bulk communication templates. Instead of manually editing each document, you can design a single template and populate it with user-specific data automatically.
12+
The Mail Merge feature in Syncfusion Blazor RichTextEditor enables developers to create dynamic, personalized documents by inserting placeholders (merge fields) into the editor content. These placeholders are later replaced with actual data at runtime, making it ideal for generating letters, invoices, and bulk communication templates.
1313

14-
To achieve this, the Rich Text Editor is customized with **custom toolbar items** and integrated with the **Mention control**. The toolbar provides two key options:
15-
- **Insert Field**: A dropdown menu that allows users to insert predefined merge fields like `{{FirstName}}` or `{{Email}}` into the editor.
16-
- **Merge Data**: A button that triggers the process of replacing all placeholders in the editor with actual values from a data source (e.g., a dictionary or database).
14+
## Key Outcomes:
1715

18-
The Mention control enhances usability by enabling users to type a special character (like `{`) and select merge fields from a popup list. This combination of toolbar customization and mention functionality makes the editor highly interactive and suitable for mail merge scenarios.
16+
- Render custom toolbar items for mail merge actions.
17+
- Insert merge fields dynamically using dropdown or Mention control.
18+
- Replace placeholders with real data using a single click.
1919

20-
## How Custom Toolbar Items Work
20+
## Rendering Custom Toolbar Items
2121

22-
Custom toolbar items are added using the `RichTextEditorCustomToolbarItems` tag inside the editor. Each item is defined with a **Name** and a **Template**. The template can include any Blazor control, such as a button or dropdown. Event handlers like `OnClickHandler` and `OnItemSelect` are used to perform actions when these items are clicked or selected.
22+
Custom toolbar items are added using the [RichTextEditorCustomToolbarItems](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.RichTextEditor.RichTextEditorCustomToolbarItems.html) tag. Each item is defined with:
2323

24-
- **Merge Data Button**: Executes the `OnClickHandler` method, which retrieves the editor content and replaces placeholders using a regex-based function.
25-
- **Insert Field Dropdown**: Displays a list of merge fields. When a field is selected, the `OnItemSelect` method inserts the corresponding placeholder into the editor at the current cursor position.
24+
- **Name**: Identifier for the toolbar item.
25+
- **Template**: Razor markup for rendering UI elements such as buttons or dropdowns.
26+
27+
{% tabs %}
28+
{% highlight razor %}
29+
30+
<RichTextEditorCustomToolbarItems>
31+
<RichTextEditorCustomToolbarItem Name="MergeData">
32+
<Template>
33+
<SfButton OnClick="MergeData">Merge Data</SfButton>
34+
</Template>
35+
</RichTextEditorCustomToolbarItem>
36+
<RichTextEditorCustomToolbarItem Name="InsertField">
37+
<Template>
38+
<SfDropDownButton Items="@items">
39+
<ChildContent>Insert Field</ChildContent>
40+
<DropDownButtonEvents ItemSelected="InsertField" />
41+
</SfDropDownButton>
42+
</Template>
43+
</RichTextEditorCustomToolbarItem>
44+
</RichTextEditorCustomToolbarItems>
45+
46+
{% endhighlight %}
47+
{% endtabs %}
48+
49+
## Executing Merge Data Action
50+
51+
When the `Merge Data` button is clicked:
52+
53+
1. The editor’s current content (rte.Value) is retrieved.
54+
2. A regex-based function scans for placeholders in the format {{FieldName}}.
55+
3. Each placeholder is replaced with its corresponding value from a dictionary.
56+
57+
```csharp
58+
59+
public void OnClickHandler()
60+
{
61+
if (this._mailMergeEditor != null)
62+
{
63+
var editorContent = this._mailMergeEditor.Value;
64+
var mergedContent = ReplacePlaceholders(editorContent, this._placeholderData);
65+
_rteValue = mergedContent;
66+
}
67+
}
68+
public static string ReplacePlaceholders(string template, Dictionary<string, string> data)
69+
{
70+
return Regex.Replace(template, @"{{\s*(\w+)\s*}}", match =>
71+
{
72+
string key = match.Groups[1].Value.Trim();
73+
return data.TryGetValue(key, out var value) ? value : match.Value;
74+
});
75+
}
76+
77+
```
78+
This ensures all placeholders are dynamically replaced without manual editing.
79+
80+
## Populating and Using Insert Field Dropdown
81+
82+
The `Insert Field` dropdown is populated from a predefined list of merge fields (items). When a user selects an item:
83+
84+
- The `InsertField()` method retrieves the corresponding field value.
85+
- It constructs an HTML snippet with a non-editable span containing the placeholder.
86+
- The snippet is inserted at the current cursor position using [ExecuteCommandAsync](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.RichTextEditor.SfRichTextEditor.html#Syncfusion_Blazor_RichTextEditor_SfRichTextEditor_ExecuteCommandAsync_Syncfusion_Blazor_RichTextEditor_CommandName_System_String_Syncfusion_Blazor_RichTextEditor_ExecuteCommandOption_).
87+
88+
```csharp
89+
public async Task OnItemSelect(MenuEventArgs args)
90+
{
91+
if (args.Item.Text != null)
92+
{
93+
var value = _mergeData.FirstOrDefault(md => md.Text == args.Item.Text)?.Value;
94+
string htmlContent = $"<span contenteditable=\"false\" class=\"e-mention-chip\"><span>{{{{{value}}}}}</span></span> ";
95+
var undoOption = new ExecuteCommandOption { Undo = true };
96+
this._mailMergeEditor.ExecuteCommandAsync(CommandName.InsertHTML, htmlContent, undoOption);
97+
await this._mailMergeEditor.SaveSelectionAsync();
98+
}
99+
}
100+
```
101+
## Role of Mention Control in Mail Merge
102+
103+
Mention control enhances usability by enabling inline field suggestions:
104+
105+
- Activated when the user types `{` inside the editor.
106+
- Displays a popup list of available merge fields from DataSource.
107+
- On selection, inserts the placeholder using the same logic as the dropdown.
108+
109+
{% tabs %}
110+
{% highlight razor %}
111+
112+
<SfMention DataSource="_mergeData" TItem="MergeData" Target="#_mailMergeEditor" MentionChar="_mentionChar" AllowSpaces="true" PopupWidth='250px' PopupHeight='200px' @ref="mentionObj">
113+
<DisplayTemplate>
114+
<span>{{@((context as MergeData).Value)}}</span>
115+
</DisplayTemplate>
116+
<ChildContent>
117+
<MentionFieldSettings Text="Text"></MentionFieldSettings>
118+
</ChildContent>
119+
</SfMention>
120+
121+
{% endhighlight %}
122+
{% endtabs %}
123+
124+
This feature is ideal for users who prefer keyboard-driven workflows.
125+
126+
## Maintaining Cursor Position During Dropdown Operations
127+
128+
When the `Insert Field` dropdown opens, the editor loses its current selection because focus shifts to the popup. To ensure the placeholder is inserted at the correct position:
129+
130+
- **SaveSelectionAsync()** is called when the dropdown opens. This stores the current cursor position in the editor before focus changes.
131+
- **RestoreSelectionAsync()** is called when the dropdown closes. This restores the saved cursor position so that the next insertion happens exactly where the user intended.
132+
133+
**Why is this important?** Without saving and restoring the selection, placeholders might be inserted at the wrong location (e.g., at the end of the content), breaking the user experience.
134+
135+
```csharp
136+
public async Task OnDropDownOpen()
137+
{
138+
if (this._mailMergeEditor != null)
139+
{
140+
await this._mailMergeEditor.SaveSelectionAsync();
141+
}
142+
}
143+
public async Task OnDropDownClose()
144+
{
145+
if (this._mailMergeEditor != null)
146+
{
147+
await this._mailMergeEditor.RestoreSelectionAsync();
148+
}
149+
}
150+
```
151+
152+
153+
## Handling Editor Mode Changes with OnActionComplete
154+
155+
The [OnActionComplete](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.RichTextEditor.RichTextEditorEvents.html#Syncfusion_Blazor_RichTextEditor_RichTextEditorEvents_OnActionComplete) event fires after specific actions in the RichTextEditor, such as switching between Source Code and Preview modes.
156+
157+
- When entering **Source Code mode**, custom toolbar buttons (Merge Data, Insert Field) should be disabled because HTML editing is manual in this mode.
158+
- When returning to **Preview mode**, these buttons are re-enabled for normal usage.
159+
160+
```csharp
161+
private void OnActionCompleteHandler(Syncfusion.Blazor.RichTextEditor.ActionCompleteEventArgs args)
162+
{
163+
if (args.RequestType == "SourceCode")
164+
{
165+
this._buttonClass = "e-tbar-btn e-tbar-btn-text e-overlay";
166+
this._dropDownButtonClass = "e-rte-elements e-rte-dropdown-menu e-overlay";
167+
this._sourceCodeEnabled = true;
168+
}
169+
if (args.RequestType == "Preview")
170+
{
171+
this._buttonClass = "e-tbar-btn e-tbar-btn-text";
172+
this._dropDownButtonClass = "e-rte-elements e-rte-dropdown-menu";
173+
this._sourceCodeEnabled = false;
174+
}
175+
}
176+
```
177+
178+
**Why is this important?** This prevents users from triggering merge operations or inserting fields while editing raw HTML, which could cause unexpected behavior.
26179

27180
{% highlight cshtml %}
28181

29182
{% include_relative code-snippet/mail-merge.razor %}
30183

31184
{% endhighlight %}
32185

33-
![Blazor RichTextEditor Mail Merge](./images/blazor-richtexteditor-mail-merge.png)
186+
![Blazor RichTextEditor Mail Merge](./images/blazor-richtexteditor-mail-merge.png)
187+
188+
## Related Resources
189+
190+
[Mention Control Guide](https://blazor.syncfusion.com/documentation/mention/getting-started-webapp)

0 commit comments

Comments
 (0)