cuba-platform / documentation

CUBA Platform Documentation
https://www.cuba-platform.com
Creative Commons Attribution 4.0 International
26 stars 45 forks source link

Replace the example of using the legacy screen API for sending emails #625

Closed GlebDurygin closed 4 years ago

GlebDurygin commented 4 years ago

Environment

Description of the bug or enhancement

The example uses legacy screen methods. They need to be replaced with new ones. An example of using the new screen API for platform version 7.1 - https://www.cuba-platform.com/discuss/t/error-when-sending-email/11059/3

An example of using the new screen API for platform version 7.2:

@UiController("sample_NewsItem.edit")
@UiDescriptor("news-item-edit.xml")
@EditedEntityContainer("newsItemDc")
@LoadDataBeforeShow
public class NewsItemEdit extends StandardEditor<NewsItem> {

    // Indicates that a new item was created in this editor
    private boolean justCreated;

    @Inject
    protected EmailService emailService;
    @Inject
    protected Dialogs dialogs;

    // This method is invoked when a new item is initialized
    @Subscribe
    public void onInitEntity(InitEntityEvent<NewsItem> event) {
        justCreated = true;
    }

    @Subscribe(target = Target.DATA_CONTEXT)
    public void onPostCommit(DataContext.PostCommitEvent event) {
        if (justCreated) {
            // If a new entity was saved to the database, ask a user about sending an email
            dialogs.createOptionDialog()
                    .withCaption("Email")
                    .withMessage("Send the news item by email?")
                    .withType(Dialogs.MessageType.CONFIRMATION)
                    .withActions(
                            new DialogAction(DialogAction.Type.YES) {
                                @Override
                                public void actionPerform(Component component) {
                                    sendByEmail();
                                }
                            },
                            new DialogAction(DialogAction.Type.NO)
                    )
                    .show();
        }
    }

    // Queues an email for sending asynchronously
    private void sendByEmail() {
        NewsItem newsItem = getEditedEntity();
        EmailInfo emailInfo = EmailInfoBuilder.create()
                .setAddresses("john.doe@company.com,jane.roe@company.com") // recipients
                .setCaption(newsItem.getCaption()) // subject
                .setFrom(null) // the "from" address will be taken from the "cuba.email.fromAddress" app property
                .setTemplatePath("com/company/demo/templates/news_item.txt") // body template
                .setTemplateParameters(Collections.singletonMap("newsItem", newsItem)) // template parameters
                .build();
        emailService.sendEmailAsync(emailInfo);
    }
}