+1-888-365-2779
Try Now
More in this section

Forums / Developing with Sitefinity / creating a usercontrol with a rad editor

creating a usercontrol with a rad editor

3 posts, 0 answered
  1. Annie
    Annie avatar
    46 posts
    Registered:
    11 Aug 2012
    07 Sep 2012
    Link to this post
    Hi,

    I would like to create a usercontrol using a rad editor. how do I go about doing that?

    Thanks,
    Annie
  2. MB
    MB avatar
    302 posts
    Registered:
    09 Jan 2005
    11 Sep 2012
    Link to this post
    I use the RadEditor for things like custom contact forms, etc.

    Basically, your usercontrol.ascx (or customcontrol embedded template) needs a establish reference to the editor.
    <%@ Register tagprefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI" %>
     
    ...blah blah blah...
     
    <telerik:RadEditor runat="server" id="myEditor" />
     
    ...blah blah blah...

    Your Code-Behind needs to use the value
    something = myEditor.Content   // HTML value
     
    or
     
    something = myEditor.Text     // Text value

    Optionally, you might want to persist the text (or html) value somewhere
    public string EditorText
            {
                get;
                set;
            }

    and perhaps set/get the value to/from the editor
    MyEditor.Text = EditorText;  // Loading the editor with a text value
     
    EditorText = MyEditor.Text  // Saving the editor's text value

    You can go the rats with styling, custom events, and various property settings of the editor, but basically it's pretty straight-forward just to get it up and running.
  3. Renato
    Renato avatar
    2 posts
    Registered:
    07 Jun 2013
    24 Jul 2013 in reply to MB
    Link to this post
    Hi, I created a User Control where the RadEditor.Text is returning Empty

    COMMENTS.ASCX
    <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
    <%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
    <%@ Import Namespace="Microsoft.SharePoint" %>
    <%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControl1.ascx.cs" Inherits="Expertime.PublishingComments.CONTROLTEMPLATES.UserControl1" %>
    <%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI, Version=2013.2.611.45, Culture=Neutral, PublicKeyToken=121fae78165ba3d4" %>
    <%@Register TagPrefix="SharePointPortalControls" Namespace="Microsoft.SharePoint.Portal.WebControls" Assembly="Microsoft.SharePoint.Portal, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <style type="text/css">
        /* The following CSS needs to be copied to the page to produce textbox-like RadEditor */ .reWrapper_corner, .reWrapper_center {
            display: none !important;
        }
     
        .reLeftVerticalSide, .reRightVerticalSide, .reToolZone, .reToolCell {
            background: white !important;
        }
     
        .reContentCell {
            border-width: 0 !important;
        }
     
        .RadEditor {
            filter: chroma(color=c2dcf0);
        }
    </style>
    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
     
        <script type="text/javascript">
            var currentLoadingPanel = null;
            var btSubmit = null;
            function RequestStart(sender, args) {
                currentLoadingPanel = $find("<%= RadAjaxLoadingPanel1.ClientID%>");
                btSubmit = "<%= panlcomments.ClientID %>";
                //show the loading panel over the updated control
                currentLoadingPanel.show(btSubmit);
     
            }
            function ResponseEnd() {
                //hide the loading panel and clean up the global variables
                currentLoadingPanel.hide(btSubmit);
                //clear
                btSubmit.SetHtml("");
                currentLoadingPanel = null;
                btSubmit = null;
     
     
            }
        </script>
    </telerik:RadCodeBlock>
    <div class="ftv-wp-title">
         <asp:Literal runat="server" ID="HeaderTitle"></asp:Literal>
            </div>
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="btSubmit">
                <UpdatedControls>
     
                    <telerik:AjaxUpdatedControl ControlID="newCommentLiteral" LoadingPanelID="RadAjaxLoadingPanel1" />
                    <telerik:AjaxUpdatedControl ControlID="panlcomments" LoadingPanelID="RadAjaxLoadingPanel1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
        <ClientEvents OnRequestStart="RequestStart" OnResponseEnd="ResponseEnd" />
    </telerik:RadAjaxManager>
    <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" BackgroundPosition="Center" Skin="Vista">
    </telerik:RadAjaxLoadingPanel>
     
     
     
    <div class="ftv-content-social ftv-type2">
                                            <div class="ftv-comments">
                                                <a class="ftv-entry-comments" ><asp:Label runat="server" ID="NbCommentsLbl"/></a>
                                            </div>
                                            <div class="ftv-notes">
                                                  <a>Note</a>
            <SharePointPortalControls:AverageRatingFieldControl ID="PageRatingControl" FieldName="AverageRating"    runat="server"/>
                                            </div>
    </div>
    <div class="Exp-Comments" id="ExpComments">
         <asp:Literal ID="existingComments" runat="server"></asp:Literal>
    </div>
     
     
     
    <asp:Literal ID="newCommentLiteral" runat="server"></asp:Literal>
    <!-- on masque le control pour les anonymes -->
     
    <asp:Panel ID="panlcomments" runat="server">
        <div class="exp-comment-message" style="display: none;">
            <asp:Label Visible="false" ID="lblMessage" Text="Messages :" runat="server"></asp:Label></div>
     
        <div class="ftv-wp-title ftv-reagir">laissez un commentairex</div>
     
        <div class="ftv-reagir-comment">
            <telerik:RadEditor ID="reComment" runat="server" EditModes="Design" ToolbarMode="ShowOnFocus" ToolsWidth="170px" Width="412px" Height="72px">
     
                <Tools>
                    <telerik:EditorToolGroup>
                        <telerik:EditorTool Name="Bold" />
                        <telerik:EditorTool Name="Italic" />
                        <telerik:EditorTool Name="StrikeThrough" />
                        <telerik:EditorTool Name="Underline" />
                        <telerik:EditorTool Name="InsertUnorderedList" />
                        <telerik:EditorTool Name="InsertOrderedList" />
                    </telerik:EditorToolGroup>
                </Tools>
            </telerik:RadEditor>
            <span class="exp-bout-comm">
                <asp:Button ID="btSubmit" runat="server" Text="Valider" OnClick="btSubmit_Click" /></span>
            <%--<span class="exp-bout-comm"><asp:Button ID="btSubmit" runat="server" Text="Valider" OnClick="btSubmit_Click" CssClass="Exp-Comment-Submit"/></span>--%>
        </div>
    </asp:Panel>
     
    <asp:Panel ID="pnelAnonyme" runat="server">
    </asp:Panel>

    COMMENTS.CS
    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Publishing;
    using Telerik.Web.UI;
    using System.Data;
     
     
    namespace Expertime.PublishingComments.CONTROLTEMPLATES
    {
        public partial class UserControl1 : UserControl
        {
            #region Controls
            private string _ValidationGroupId;
            private ValidationSummary _ErrorContainer;
            private ScriptManager _AjaxManager;
            #endregion
     
            #region vars & cons
            const string CommentListUrl = "ExpertimePublishingComments", CommentListTitle = "Expertime Comments";
            const string ExpertimePublishingCommentSiteFeatureId = "68af5cec-59a1-4105-97a7-3fb7b68fbf46";
            const string FieldName_ListItemId = "ListItemId", FieldName_CommentBody = "CommentBody";
            #endregion
     
            #region properties
            public ScriptManager AjaxManager
            {
     
                get { return _AjaxManager; }
     
                set { _AjaxManager = value; }
     
            }
            #endregion
     
            protected override void CreateChildControls()
            {
                base.CreateChildControls();
                if (ScriptManager.GetCurrent(Page) == null)
                {
                    ScriptManager sMgr = new ScriptManager();
                    Page.Form.Controls.AddAt(0, sMgr);
     
                }
                string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
                try
                {
                    if (!string.IsNullOrEmpty(formOnSubmitAtt) && formOnSubmitAtt == "return _spFormOnSubmitWrapper();")
                    {
     
                        Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
     
                    }
                }
                catch { }
                try
                {
                    //if (btSubmit == null)
                    //    btSubmit = this.FindControl("btSubmit") as Button;
     
                    //if (reComment == null)
                    //    reComment = this.FindControl("reComment") as RadEditor;
     
                    //if (existingComments == null)
                    //    existingComments = this.FindControl("existingComments") as Literal;
     
                    //if (gv1 == null)
                    //    gv1 = this.FindControl("gv1") as GridView;
     
                    //if (newCommentLiteral == null)
                    //    newCommentLiteral = this.FindControl("newCommentLiteral") as Literal;
     
                    GetExistingComments();
                }
                catch (Exception exc)
                {
                    existingComments.Text = string.Format("<span class=\"Exp-Error\">{0}</span>", exc.Message);
                }
                if (SPContext.Current.Web.CurrentUser == null)
                {
                    panlcomments.Visible = false;
                    pnelAnonyme.Visible = true;
                }
                else
                {
                    panlcomments.Visible = true;
                    pnelAnonyme.Visible = false;
                }
                if (!this.Controls.Contains(_ErrorContainer))
                {
                    _ValidationGroupId = Guid.NewGuid().ToString();
                    _ErrorContainer = new ValidationSummary();
                    _ErrorContainer.ID = "_ErrorContainer";
                    _ErrorContainer.ValidationGroup = _ValidationGroupId;
                    _ErrorContainer.BorderStyle = BorderStyle.Solid;
                    _ErrorContainer.BorderWidth = Unit.Pixel(3);
                    _ErrorContainer.BorderColor = System.Drawing.Color.Red;
                    this.Controls.Add(_ErrorContainer);
                }
     
                Literal HeaderTitle = this.FindControl("HeaderTitle") as Literal;
                if (HeaderTitle == null) throw new ArgumentNullException("le controle HeaderTitle n'existe pas");
     
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                    HeaderTitle.Text = "Réagir";
                else
                {
                    HeaderTitle.Text = "<div class='ftv-wp-title ftv-title-separator'>Réagir</div>" +
                                       "<div class='ftv-offline'><a><h6>Connectez-vous</h6> pour réagir</a></div>";
                }
     
            }
     
            private void GetExistingComments()
            {
                Guid siteId = SPContext.Current.Site.ID, webId = SPContext.Current.Web.ID;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite elevatedSite = new SPSite(siteId))
                    {
                        using (SPWeb elevatedWeb = elevatedSite.OpenWeb(webId))
                        {
                            try
                            {
                                string prefixUrl = elevatedWeb.ServerRelativeUrl == "/" ? "/" : elevatedWeb.ServerRelativeUrl + "/";
                                SPList commentList = elevatedWeb.GetList(prefixUrl + CommentListUrl);
                                SPQuery query = new SPQuery();
                                string queryString = @"<OrderBy>
                                                          <FieldRef Name=""Created"" Ascending=""True"" />
                                                       </OrderBy>
                                                       <Where>
                                                          <Eq>
                                                             <FieldRef Name=""ListItemId"" />
                                                             <Value Type=""Text"">{0}</Value>
                                                          </Eq>
                                                       </Where>";
                                query.Query = string.Format(queryString, SPContext.Current.ListItem.UniqueId.ToString());
                                SPListItemCollection items = commentList.GetItems(query);
                                StringBuilder sb = new StringBuilder();
     
                                var NbCommentsLbl = this.FindControl("NbCommentsLbl") as Label;
                                if (NbCommentsLbl == null) throw new ArgumentNullException("le controle NbCommentsLbl n'existe pas");
     
                                if (items.Count <= 1)
                                    NbCommentsLbl.Text = String.Format("{0} commentaire", items.Count.ToString());
                                else
                                    NbCommentsLbl.Text = String.Format("{0} commentaires", items.Count.ToString());
     
     
                                //  SPField fieldListItemId = commentList.Fields.GetFieldByInternalName(FieldName_ListItemId);
                                SPField fieldCommentBody = commentList.Fields.GetFieldByInternalName(FieldName_CommentBody);
                                SPField fieldCreatedBy = commentList.Fields.GetFieldByInternalName("Author");
                                SPField fieldCreated = commentList.Fields.GetFieldByInternalName("Created");
     
                                foreach (SPListItem item in items)
                                {
                                    sb.Append("<div class=\"Exp-Comment\">");
     
                                    sb.Append("<div class=\"Exp-Comment-Header\">");
                                    sb.Append("<div class=\"Exp-Comment-Author\">");
                                    SPFieldUserValue fieldValue = fieldCreatedBy.GetFieldValue(item[fieldCreatedBy.Id].ToString()) as SPFieldUserValue;
                                    string userDisplayName = fieldValue.User.Name;
                                    sb.AppendFormat("<a style=\"cursor:text; TEXT-DECORATION: none;\">Publié par {0}</a>", userDisplayName);
                                    sb.Append("</div>");
                                    sb.Append("<div class=\"Exp-Comment-Date\">");
                                    sb.Append(item[fieldCreated.Id].ToString());
                                    sb.Append("</div>");
                                    sb.Append("</div>");
     
                                    sb.Append("<div class=\"Exp-Comment-Body\">");
                                    sb.Append(item[fieldCommentBody.Id].ToString());
                                    sb.Append("</div>");
     
                                    sb.Append("</div>");
                                }
     
                                existingComments.Text = sb.ToString();
                            }
                            catch
                            {
                                //la liste n'existe pas
                                StringBuilder sb = new StringBuilder();
                                sb.Append("<div id=\"ExpComments\" class=\"Exp-Comments\">");
                                sb.Append("<div class=\"Exp-Comments-Number\"><span class=\"Exp-Comments-Number-Span\" >");
                                sb.AppendFormat("{0} commentaire ", "0");
                                sb.Append("</span></div>");
                                sb.Append("</div>");
                                existingComments.Text = sb.ToString();
                            }
                        }
                    }
                });
            }
     
            protected void btSubmit_Click(object sender, EventArgs e)
            {
     
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite elevatedSite = new SPSite(SPContext.Current.Site.Url))
                        {
                            using (SPWeb elevatedWeb = elevatedSite.OpenWeb(SPContext.Current.Web.ServerRelativeUrl))
                            {
                                if (reComment.Content.Trim() != "")
                                {
                                    SPList commentList = null;
                                    try
                                    {
                                        string prefixUrl = elevatedWeb.ServerRelativeUrl == "/" ? "/" : elevatedWeb.ServerRelativeUrl + "/";
                                        commentList = elevatedWeb.GetList(prefixUrl + CommentListUrl);
                                    }
                                    catch
                                    {
                                    }
                                    //if the comment list cannot be found we create it
                                    if (commentList == null)
                                    {
                                        elevatedWeb.AllowUnsafeUpdates = true;
                                        Guid newListId = elevatedWeb.Lists.Add(CommentListTitle, "", CommentListUrl, ExpertimePublishingCommentSiteFeatureId, 100, "", SPListTemplate.QuickLaunchOptions.Off);
                                        commentList = elevatedWeb.Lists[newListId];
                                        elevatedWeb.AllowUnsafeUpdates = false;
                                    }
                                    SPList list = commentList;
     
     
                                    elevatedWeb.AllowUnsafeUpdates = true;
                                    //creating the comment item
                                    SPListItem newComment = list.Items.Add();
                                    SPField fieldListItemId = list.Fields.GetFieldByInternalName(FieldName_ListItemId);
                                    SPField fieldCommentBody = list.Fields.GetFieldByInternalName(FieldName_CommentBody);
                                    SPField fieldCreatedBy = list.Fields.GetFieldByInternalName("Author");
                                    newComment[fieldListItemId.Id] = SPContext.Current.ListItem.UniqueId.ToString();
                                    newComment[fieldCommentBody.Id] = reComment.Content;
                                    SPFieldUserValue val = new SPFieldUserValue(SPContext.Current.Web, SPContext.Current.Web.CurrentUser.ID, SPContext.Current.Web.CurrentUser.LoginName);
                                    newComment[fieldCreatedBy.Id] = val;
                                    newComment.SystemUpdate();
     
                                    elevatedWeb.AllowUnsafeUpdates = false;
     
                                    //updating the new comment in the display
                                    StringBuilder sb = new StringBuilder();
                                    sb.Append("<div class=\"Exp-Comment\">");
     
                                    sb.Append("<div class=\"Exp-Comment-Header\">");
                                    sb.Append("<div class=\"Exp-Comment-Author\">");
     
                                    string userDisplayName = SPContext.Current.Web.CurrentUser.Name;
                                    string userEmail = SPContext.Current.Web.CurrentUser.Email;
                                    sb.AppendFormat("<a style=\"cursor:text; TEXT-DECORATION: none;\">{1}</a>", userEmail, userDisplayName);
                                    sb.Append("</div>");
                                    sb.Append("<div class=\"Exp-Comment-Date\">");
                                    sb.Append(DateTime.Now.ToLongDateString());
                                    sb.Append("</div>");
                                    sb.Append("</div>");
                                    sb.Append("<div class=\"Exp-Comment-Body\">");
                                    sb.Append(reComment.Content);
                                    sb.Append("</div>");
     
                                    sb.Append("</div>");
     
                                    newCommentLiteral.Text = sb.ToString();
                                    //reComment.Content = string.Empty;
                                    //btSubmit.Visible = false;
     
                                    //reComment.Visible = false;
                                    //btSubmit.Visible = false;
                                    //lblMessage.Visible = false;
                                }
                            }
                        }
                    });
                }
                catch
                {
                }
            }
     
     
     
            public void RegisterError(string message)
            {
     
                if (this.Controls.Contains(_ErrorContainer))
                {
     
                    //this way of generating a unique control id is used in some of the OOB web parts
     
                    int uniqueCounter;
     
                    if (HttpContext.Current.Items["GetUniqueControlId"] != null)
                    {
     
                        uniqueCounter = (int)HttpContext.Current.Items["GetUniqueControlId"];
     
                    }
     
                    else
                    {
     
                        uniqueCounter = 0;
     
                    }
     
                    uniqueCounter++;
     
                    HttpContext.Current.Items["GetUniqueControlId"] = uniqueCounter;
     
     
     
                    //create a custom validator to register the current error message with the ValidationSummary control
     
                    CustomValidator cv = new CustomValidator();
     
                    cv.ID = string.Concat("_Error_", uniqueCounter);
     
                    cv.ValidationGroup = _ValidationGroupId;
     
                    cv.Display = ValidatorDisplay.None;
     
                    cv.IsValid = false;
     
                    cv.ErrorMessage = message;
     
     
     
                    this.Controls.Add(cv);
     
                }
     
                else
                {
     
                    //if RegisterError is called before the CreateChildControls override in AjaxBasePart then transfer the user to an error page using the SPUtility
     
                    Microsoft.SharePoint.Utilities.SPUtility.TransferToErrorPage("The CreateChildControls function of the AjaxBasePart has not been called.  You probably need to add \"base.CreateChildControls()\" to the top of your CreateChildControls override.");
     
                }
     
            }
            //protected void Page_Load(object sender, EventArgs e)
            //{
            //}
        }
    }


3 posts, 0 answered