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

Forums / Developing with Sitefinity / Image selector and Rich Text editor on custom backend page?

Image selector and Rich Text editor on custom backend page?

4 posts, 0 answered
  1. Steve
    Steve avatar
    13 posts
    Registered:
    29 Apr 2011
    08 Jun 2012
    Link to this post
    I am working on a custom backend page that selects a single custom module item. I need to need able to pick an image from the image library and also edit content (Rich Text) on the page. My custom module has two images to select and one Rich Text field.

    Most custom module & widget examples show plain text. How can I do this with more complex data types such as the image and rich text?
  2. Stoimen Stoimenov
    Stoimen Stoimenov avatar
    60 posts
    Registered:
    11 Jul 2016
    12 Jun 2012
    Link to this post
    Hi Steve,

    Thank you for contacting us.

    Unfortunately it is not very clear for me what you are actually trying to achieve. First of all are you using a custom module built using code or the Module Builder tool? If you are using the Module Builder you could just create a new backend page, drop the custom module widget on the page and your data will be displayed. 

    After your module is created using the module builder you can create content items and for them select images from your libraries. 

    Here you can find documentation for the Module Builder.

    Please provide more details about your problems so that we can help. Feel free contacting us if you need further assistance.

    Regards,
    Stoimen Stoimenov
    the Telerik team
    Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  3. Steve
    Steve avatar
    13 posts
    Registered:
    29 Apr 2011
    12 Jun 2012
    Link to this post
    I already have a widget based on a UserControl. What I need to know is how to add an image selector and rich text content editor to the widget.
  4. Brett Whittington
    Brett Whittington avatar
    89 posts
    Registered:
    10 Aug 2012
    13 Jun 2012
    Link to this post
    Hi Steve.  I am also confused on what you are trying to do but I'll attempt to answer based on what I think you are trying to do.  I think you have an "intra-site" module that you are trying to add a image selector and a rich content control to.  If this is not the case, you can stop reading. 

    I struggled with this for weeks because I could not figure out how all the examples in the forums and blog posts related to what I was trying to do.  All of the examples I found were widgets that were used when clicking the edit button of a control.  On a module backend, there isn't an edit button to do a widget so the example didn't seem to apply.  Here is the code for the Add/Edit view page of my module that included a Image Selector, Page Selector and Rich Text Editor.

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FeaturedMessagesAddEditView.ascx.cs" Inherits="InstalledWebComponents.Modules.FeaturedMessages.Admin.FeaturedMessagesAddEditView" %>
    <%@ Register Assembly="Telerik.Sitefinity" Namespace="Telerik.Sitefinity.Web.UI.Fields" TagPrefix="sf" %>
    <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
    <%@ Register Assembly="Telerik.Sitefinity" Namespace="Telerik.Sitefinity.Web.UI" TagPrefix="sitefinity" %>
    <%@ Register Assembly="Telerik.Sitefinity" Namespace="Telerik.Sitefinity.Web.UI.Fields" TagPrefix="sfFields" %>
    <%@ Register Assembly="Telerik.Sitefinity" TagPrefix="designers" Namespace="Telerik.Sitefinity.Web.UI.ControlDesign" %>
    <%@ Register Assembly="Telerik.Sitefinity" Namespace="Telerik.Sitefinity.Modules.Libraries.Web.UI.Designers" TagPrefix="sf1" %>
    <telerik:RadScriptManager ID="manager" runat="server"></telerik:RadScriptManager>
    <!-- This is needed for the Page Selector to work -->
    <sitefinity:UserPreferences ID="userPreferences" runat="server" />
    <h1 class="sfBreadCrumb">Sample Control</h1>
    <div class="sfMain sfClearfix">
        <div class="sfContent">
            <div class="rgTopOffset sfWorkArea">
                <fieldset class="sfNewContentForm">
                    <div class="sfFormIn">
                        <ul>
                            <li>
                                <asp:Label ID="lblBlurb" runat="server" Text="Blurb" CssClass="sfTxtLbl" />
                    <!-- Rich Text Editor -->
                                <telerik:RadEditor ID="radblurb" runat="server"></telerik:RadEditor>
                            </li>
                            <li>
                    <!-- Media Content Selector -->
                                <sf1:MediaContentSelectorView ID="selectorView" runat="server" ContentType="Telerik.Sitefinity.Libraries.Model.Image"
                                    ParentType="Telerik.Sitefinity.Libraries.Model.Album" LibraryBinderServiceUrl="~/Sitefinity/Services/Content/AlbumService.svc/"
                                    MediaContentBinderServiceUrl="~/Sitefinity/Services/Content/ImageService.svc/"
                                    MediaContentItemsListDescriptionTemplate="Telerik.Sitefinity.Resources.Templates.Designers.Libraries.Images.ImageItemDescriptionTemplate.htm"
                                    DisplayResizingOptionsControl="false" ShowOpenOriginalSizeCheckBox="false">
                                </sf1:MediaContentSelectorView>
                            </li>
                            <li>
                                <asp:Label ID="lblRelatedLink" runat="server" Text="RelatedLink" CssClass="sfTxtLbl" />
                    <!-- Page Selector -->
                                <sitefinity:GenericPageSelector
                                    id="GenericPageSelector1"
                                    runat="server"
                                    RootNodeID="F669D9A7-009D-4d83-DDAA-000000000002"
                                    WebServiceUrl="~/Sitefinity/Services/Pages/PagesService.svc/"
                                    ShowOnlySelectedAsGridOnLoad="true"
                                    MarkItemsWithoutTranslation="false"
                                    AllowMultipleSelection="false"/>
                            </li>
                            <asp:HiddenField ID="imageId" runat="server" ClientIDMode="Static" />
                            <asp:HiddenField ID="pageId" runat="server" ClientIDMode="Static" />
                        </ul>
                        <p><asp:Button ID="btnSave" runat="server" Text="Save Sample" OnClick="btnSave_Click" />
                            or <a href="<%= ResolveUrl("~/Sitefinity/Content/Sample") %>">Cancel and
                                go back to Featured Messages</a></p>
                    </div>
                </fieldset>
            </div>
        </div>
    </div>

    Here is the backend for that page.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Telerik.Sitefinity;
    using Telerik.Sitefinity.Data;
    using Telerik.Sitefinity.Model;
    using Telerik.Sitefinity.Modules;
    using Telerik.Sitefinity.Libraries;
    using Telerik.Sitefinity.Libraries.Model;
    using Telerik.Sitefinity.Modules.Libraries;
    using Telerik.Sitefinity.Modules.Libraries.Images;
    using Telerik.Sitefinity.Modules.Pages;
    using Telerik.Sitefinity.Modules.Pages.Web.UI;
    using Telerik.Sitefinity.Taxonomies;
    using Telerik.Sitefinity.Taxonomies.Model;
    using Telerik.Sitefinity.Web;
    using Telerik.Sitefinity.Web.UI.ControlDesign;
    using Telerik.Sitefinity.Web.UI.Fields;
    using Telerik.Sitefinity.Resources;
    using Telerik.Web.UI;
     
    namespace SampleControl
    {
        //Ned to implement the IScriptControl interface so the User Control can use Widgets
        public partial class SampleControlAddEditView : System.Web.UI.UserControl, IScriptControl
        {
            private const string UrlNameCharsToReplace = @"[^\w\-\!\$\'\(\)\=\@\d_]+";
            private const string UrlNameReplaceString = "-";
            SampleControlcontext = SampleControlContext.Get();
     
            private ScriptManager sm;
         
            #region Check Mode
     
            public enum AdminControlMode
            {
                Create,
                Edit
            }
     
            /// <summary>
            /// Gets or sets the mode in which to render the control.
            /// </summary>
            /// <value>
            /// The mode.
            /// </value>
            public AdminControlMode Mode { get { return _mode; } set { _mode = value; } }
            private AdminControlMode _mode;
     
            private Guid SampleControlID = Guid.Empty;
     
            /// <summary>
            /// Gets the SampleControl ID to load in Edit Mode.
            /// </summary>
            protected Guid SampleControlID
            {
                get
                {
                    if (SampleControlID == Guid.Empty)
                    {
                        // ensure parameter is valid
                        var param = Request.RequestContext.RouteData.Values["Params"] as string[];
                        if (param == null) return Guid.Empty;
     
                        // grab id from url
                        Guid id;
                        if (!Guid.TryParse(param[0], out id)) return Guid.Empty;
     
                        // retrieve SampleControl
                        var SampleControl= context.SampleControl.FirstOrDefault(t => t.Id == id);
                        SampleControlID = (SampleControl == null) ? Guid.Empty : SampleControl.Id;
                    }
                    return SampleControlID;
                }
            }
     
            #endregion
     
            /// <summary>
            /// Handles the Load event of the Page control.
            /// </summary>
            /// <param name="sender">The source of the event.</param>
            /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack && Mode == AdminControlMode.Edit)
                {
     
                    var SampleControl= context.SampleControl.Where(t => t.Id == SampleControl).FirstOrDefault();
                    if SampleControl== null) return;
     
     
                    Telerik.Sitefinity.Libraries.Model.Image image = App.WorkWith().Images().Where(i => i.Id == SampleControl.ImageId).Get().SingleOrDefault();
                    Telerik.Sitefinity.Pages.Model.PageNode page = App.WorkWith().Pages().Where(p => p.Id == SampleControl.RelatedLink).Get().SingleOrDefault();
     
                    radblurb.Content = SampleControl.Blurb;
                    pageId.Value = SampleControl.RelatedLink.ToString();
                    imageId.Value = SampleControl.ImageId.ToString();
                }
            }
     
            protected override void OnPreRender(EventArgs e)
            {
                if (!this.DesignMode)
                {
                    // Test for ScriptManager and register if it exists
                    sm = RadScriptManager.GetCurrent(this.Page);
     
                    if (sm == null)
                        throw new HttpException("A ScriptManager control must exist on the current page.");
     
                    sm.RegisterScriptControl(this);
                }
     
                base.OnPreRender(e);
            }
     
            protected override void Render(HtmlTextWriter writer)
            {
                if (!this.DesignMode)
                    sm.RegisterScriptDescriptors(this);
     
                base.Render(writer);
            }
     
            protected virtual IEnumerable<ScriptReference> GetScriptReferences()
            {
                ScriptReference imageReference = new ScriptReference();
            //Path to the client script required for the media content selector
                imageReference.Path = "~/Modules/SampleControl/Admin/JavaScript/SampleControlAddEditView.js";
     
                return new ScriptReference[] { imageReference };
            }
     
            protected virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors()
            {
                ScriptControlDescriptor imageDescriptor = new ScriptControlDescriptor("InstalledWebComponents.Modules.SampleControl.Admin.SampleControlAddEditView", this.ClientID);
                //Send the MediaContentSelectorView clientside object to the page.
                imageDescriptor.AddComponentProperty("selectorView", selectorView.ClientID);
                //Send the GenericPageSelector clientside object to the page.
                imageDescriptor.AddComponentProperty("pageSelectorView", GenericPageSelector1.ClientID);
                //Send the Save Button clientside object to the page.
                imageDescriptor.AddElementProperty("saveLink", btnSave.ClientID);
                return new ScriptDescriptor[] { imageDescriptor };
            }
                 
     
            IEnumerable<ScriptReference> IScriptControl.GetScriptReferences()
            {
                return GetScriptReferences();
            }
     
            IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors()
            {
                return GetScriptDescriptors();
            }
     
     
            /// <summary>
            /// Handles the Click event of the btnSave control.
            /// </summary>
            /// <param name="sender">The source of the event.</param>
            /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
            protected void btnSave_Click(object sender, EventArgs e)
            {
                this.Page.Validate();
                if (this.Page.IsValid)
                {
                    Telerik.Sitefinity.Project.Configuration.ProjectConfig config = new Telerik.Sitefinity.Project.Configuration.ProjectConfig();
                    Telerik.Sitefinity.Project.Web.Services.ProjectInfo projectInfo = new Telerik.Sitefinity.Project.Web.Services.ProjectInfo(config);
                    switch (Mode)
                    {
                        case AdminControlMode.Edit:
     
                            // update existing SampleControl
                            var SampleControl= context.SampleControl.Where(t => t.Id == SampleControlID).FirstOrDefault();
                            if (SampleControl == null) return; // default 404 response
     
                            // mark route handled/found
                            RouteHelper.SetUrlParametersResolved();
                             
                //Code to save object.
     
                            break;
     
                        case AdminControlMode.Create:
                            //code to save object
                            break;
                    }
     
                    // save and return to main view
                    context.SaveChanges();
                    Response.Redirect(ResolveUrl(SiteMapBase.GetActualCurrentNode().ParentNode.Url));
                }
            }
     
            protected override void OnUnload(EventArgs e)
            {
                base.OnUnload(e);
                if (context != null)
                    context.Dispose();
            }
        }
    }

    Finally the javascript portion so the media content selector and generic page selector can send their data to the page.
    Type.registerNamespace("SampleNamespace");
     
    SampleNamespace.SampleControlAddEditView = function (element) {
        SampleNamespace.SampleControlAddEditView.initializeBase(this, [element]);
     
        this._imageId = $("#imageId").val();
        this._pageId = $("#pageId").val();
    }
     
    SampleNamespace.SampleControlAddEditView.prototype = {
        initialize: function () {
            SampleNamespace.SampleControlAddEditView.callBaseMethod(this, 'initialize');
            this._itemSelectDelegate = Function.createDelegate(this, this._itemSelect);
            this._selectorView.add_onItemSelectCommand(this._itemSelectDelegate);
         
        //Used to capture save button click
            this._saveLinkClickDelegate = Function.createDelegate(this, this._saveLinkClicked);
            if (this._saveLink) {
                $addHandler(this._saveLink, "click", this._saveLinkClickDelegate);
            }
         
        // Used to determine which image needs to be highlighted on page load.
            this._mediaContentBinderItemDataBoundDelegate = Function.createDelegate(this, this._mediaContentBinderItemDataBound);
     
            this._onLoadDelegate = Function.createDelegate(this, this._onLoad);
            Sys.Application.add_load(this._onLoadDelegate);
     
     
        },
     
        _onLoad: function (sender, args) {
            this._selectorView.get_mediaContentBinder().add_onItemDataBound(this._mediaContentBinderItemDataBoundDelegate);
            this._pageSelectorView.set_selectedItemId(this._pageId);
        },
     
        dispose: function () {
            SampleNamespace.SampleControlAddEditView.callBaseMethod(this, 'dispose');
            if (this._selectorView) {
                this._selectorView.add_onItemSelectCommand(this._itemSelectDelegate);
            }
     
            if (this._selectLinkClickDelegate) {
                delete this._saveLinkClickDelegate;
            }
     
        },
     
        //This method determines which image should be highlighted
        _mediaContentBinderItemDataBound: function (sender, args) {
            var dataItem = args.get_dataItem();
            var id = dataItem.Id;
            if (id == this._imageId) {
                sender._selectedItems.push(dataItem);
                this._highlightSelectedImage(args.get_itemElement());
            }
        },
     
        get_selectorView: function () {
            return this._selectorView;
        },
     
        set_selectorView: function (value) {
            this._selectorView = value;
        },
     
        get_pageSelectorView: function () {
            return this._pageSelectorView;
        },
        set_pageSelectorView: function (value) {
            this._pageSelectorView = value;
        },
     
        get_saveLink: function () {
            return this._saveLink;
        },
     
        set_saveLink: function (value) {
            this._saveLink = value;
        },
     
        //This method determines which item to select
        _itemSelect: function (sender, args) {
            this._imageId = args.get_dataItem().Id;
            $("#imageId").val(this._imageId);
            var selectedElement = args.get_itemElement();
            this._highlightSelectedImage(selectedElement);
        },
     
        //This method set the selected value of the media content selector
        _itemSet: function (sender, args) {
            var d = this.get_controlData();
            d.SelectedItemValue = this._imageId;
        },
     
        //This method adds the style so the selected item appears highlighted
        _highlightSelectedImage: function (selectedElement) {
            if (this.selectedImageElement) {
                if (this.selectedImageElement != selectedElement) {
                    $(this.selectedImageElement).find(".imgSelect").removeClass("sfSelImgBorder");
                    $(this.selectedImageElement).removeClass("sfSel");
                } else {
                    $(this.selectedImageElement).addClass("sfSel");
                }
            }
     
            if (selectedElement) {
                this.selectedImageElement = selectedElement;
                $(selectedElement).addClass("sfSel");
                $(selectedElement).find(".imgSelect").addClass("sfSelImgBorder");
            }
        },
     
        //The save button client click event.
        _saveLinkClicked: function (sender, args) {
            var selectedValue = this.get_pageSelectorView().get_selectedItem();
     
            if (!selectedValue || selectedValue === "") {
                alert("No page selected.");
            } else {
                $("#pageId").val(selectedValue.Id);
            }
        },
     
        add_onItemSelectCommand: function (delegate) {
            this.get_events().addHandler('onItemSelectCommand', delegate);
        }
    }
     
    SampleNamespace.SampleControlAddEditView.registerClass('SampleNamespace.SampleControlAddEditView', Sys.Component);
     
    if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

    The above code is basically copied and pasted from a working module I have.  I've had to remove a few things because of confidentiality so I cannot guarantee that the code will build straight of the box.  Hopefully this is what you are looking for.
4 posts, 0 answered