Search code examples
sitecoresitecore7sitecore7.2

Programatically Insert Data in the HTML tab of Rich Text Editor in Sitecore


I am programmatically importing data from Excel sheet to Sitecore items. The data in the description section has HTML tags in it. Is there a way to programmatically map the data to the HTML tab of Sitecore Rich text editor instead of the normal text tab?


Solution

  • Setting the Rich Text Editor field can be done via code below

    string html = "<div></div>";
    
    //Account with permission to edit item
    var user = Sitecore.Security.Accounts.User.FromName("username",false);
    
    using (new Sitecore.Security.Accounts.UserSwitcher(user))
    {
        try
        {
            item.Editing.BeginEdit();
    
            //Get the RichTextEditor field
            Sitecore.Data.Fields.HtmlField htmlField = item.Fields.FirstOrDefault(f => f.Name.Trim().ToLower() == fieldName.Trim().ToLower());
    
            if (htmlField != null)
            {
                htmlField.Value = html; 
            }     
        }
        catch (Exception ex)
        {
            Log.Error(ex.Message, ex, this);
            throw ex;
        }
        finally
        {
            item.Editing.EndEdit();
        }
    }