Use Custom field types to implement the parent-child relationship of the SharePoint list

Source: Internet
Author: User
Document directory
  • Instance
  • Create the "My Child Items" Field
  • Source code
  • Add a new subitem
  • Download and install the solution package

Parent-child relationships are common in real scenarios. In SharePoint, two SharePoint lists are associated by a query item field in the sublist. In this form, you can establish a parent-child relationship between lists.

We usually need to display subitems in the parent list form (DispForm. aspx, EditFrom. aspx, NewForm. aspx. To this end, I created a SharePoint Custom Field Type: "ParentChildrenField ".

Instance

The purpose of this example is to implement the navigation of a custom tab dialog box, which is used to replace the default top navigation of the SharePoint website. Therefore, I have created two SharePoint lists: Tabs and Sub-Tabs. I have created a new "Parent Tab" in the website column, which is of the query type and the data comes from the "title" of Tabs ". This column is added to the "Sub-Tabs" list.

Create the "My Child Items" Field

To Display sub-Items (sub-tabs) in the Tab form (Display, Edit, and New), I created a SharePoint website column "My Child Items ", type: ParentChildrenField ". This column is added to the parent list "Tabs. Generally, it is better to add a column to a list than to add a column to a list directly.

Source code

 

public class ParentChildrenFieldControl : TextField{    int NumOfChildren = 0;    LiteralControl literalCtrl;    SPList childList = null;    Guid listID = SPContext.Current.List.ID; //.ToString();    HyperLink linkAddNew = new HyperLink();    protected override void CreateChildControls()    {        base.CreateChildControls();        if (this.ControlMode == SPControlMode.Display ||            this.ControlMode == SPControlMode.Edit ||            this.ControlMode == SPControlMode.New)        {            literalCtrl = new LiteralControl();            base.Controls.Add(literalCtrl);            base.Controls.Add(linkAddNew);        }    }    protected override void OnLoad(EventArgs e)    {        base.OnLoad(e);        string childListname = this.Field.GetCustomProperty("ChildListName").ToString();        try        {            try            {                childList = SPContext.Current.Web.Lists[childListname];            }            catch            {                throw new ConfigurationErrorsException(@"Child List " + childListname + " doesn't exist at the site.");            }            StringBuilder sb = new StringBuilder();            try            {                SPQuery query = new SPQuery(childList.DefaultView);                query.Query = string.Format(@"                    <Where>                        <Eq>                            <FieldRef Name='{0}' LookupId='true' />                            <Value Type='Integer'>{1}</Value>                        </Eq>                    </Where>", LookupField.InternalName, this.Item.ID.ToString());                 sb.Append(childList.RenderAsHtml(query));            }            catch (Exception ex)            {                sb.Append("<p>There was an error loading the list information:<br />");                sb.Append(ex.Message);                sb.Append("</p>");            }            literalCtrl.Text = sb.ToString();                        // Add new            linkAddNew.Text = "Add New";            string navigateUrl = string.Format("/NewForm.aspx?{0}={1}&Source={2}", SPEncode.UrlEncode(LookupField.Title), SPContext.Current.ListItem.ID.ToString(), SPEncode.UrlEncode(this.Page.Request.Url.ToString()));            linkAddNew.NavigateUrl = childList.RootFolder.ServerRelativeUrl + navigateUrl;         }        catch (Exception ex)        {            literalCtrl.Text = ex.Message;        }    }    SPField _LookupField = null;    SPField LookupField    {        get        {            if (_LookupField == null) {                foreach (SPField field in childList.Fields) {                    if (field is SPFieldLookup && listID == new Guid(((SPFieldLookup)field).LookupList)) {                        _LookupField = field;                        break;                    }                }            }            return _LookupField;        }    }    protected override void Render(HtmlTextWriter output)    {        literalCtrl.RenderControl(output);        // Add New link        if (this.ControlMode == SPControlMode.Display ||            this.ControlMode == SPControlMode.Edit)            linkAddNew.RenderControl(output);    }    public override void UpdateFieldValueInItem()    {        this.EnsureChildControls();        try        {            this.Value = NumOfChildren;            this.ItemFieldValue = this.Value;        }        catch (Exception)        {            ;        }    }}

 

Add a new subitem

When a user adds a new subitem, the corresponding item in the "Parent Tab" drop-down box should be automatically selected for the user in the NewForm. aspx form. This is why we need to add the name and value of the query item field to the query string: "NewForm. aspx? Parent % 20Tab = 1 & Source = ...".

Place the following JavaScript code in NewForm. aspx of the sublist. The best place is put in "PlaceHolderBodyAreaClass.

<script type="text/javascript">var qs = location.search.substring(1, location.search.length);  var nameVal = qs.split("&")[0].split("=");  SetLookupFieldValue(unescape(nameVal[0]), nameVal[1]);    function SetLookupFieldValue(fieldName, val) {    var theSelect = getTagFromIdentifierAndTitle("select",                     "Lookup", fieldName);    if (theSelect != null) {        theSelect.value = val;        return;    }    // if theSelect is null,     // it means that the target list has more than 20 items,     // and the Lookup is being rendered with an input element    var theInput = getTagFromIdentifierAndTitle("input",                                                 "", fieldName);    theInput.value = val;}function getTagFromIdentifierAndTitle(tagName, identifier, title) {    var len = identifier.length;    var tags = document.getElementsByTagName(tagName);    for (var i = 0; i < tags.length; i++) {        var tempString = tags[i].id;        if (tags[i].title == title && (identifier == "" ||             tempString.indexOf(identifier) == tempString.length - len))            return tags[i];    }    return null;}    </script>
Download and install the solution package

The solution package "ParentChildRelationship. wsp" was developed using Visual Studio Extensions VseWSS v1.3. Open Setup. bat and set the URL of your website set and Website:

 set DefaultWebUrl=http://YourWeb set DefaultSiteUrl=http://YourSite

Then run setup. bat to complete the installation. Run setup. bat-u.

After the installation is complete, create a website bar (for example, MyChildren) with the type of ParentChildrenField. Enter the name of the sublist (not a url ). Then, add the column to the parent list.

Source code installation package

 

References

SharePoint List Parent/Child Relationship

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.