Skip to main content

Cloud

How to Make Parent-Child Lists and Forms in SharePoint 2010

In this article we will explore how to make parent-child list relationships in SharePoint 2010, at both the list level and the user interface form level. At the list level, we will describe how to use a Lookup field to create the relationship at the list level. At the user interface level, we will document a technique for using client-side JavaScript (using JQuery) to facilitate an acceptable user interaction experience for creating and maintaining of the parent-child relationships.
Most SharePoint administrators doing this for the first time can figure out the list-relationship part of it easily enough. Where it gets tricky (and interesting) is in the customization of the user interface forms to allow your end users to view, edit, and add items between the parent and child lists.

User Interaction and Data Quality

By “acceptable user interaction experience” we mean the following:

  • We do not want the user to work too hard in trying to figure out how to create a parent-child relationship in the user interface. It should be obvious to discern what the current relationship is, if any has been set, and it should be obvious how to set or change the relationship.
  • The user should be able to create a new child item while looking at a parent item. When the New Item form of the child item comes up, the parent item should be pre-selected.
  • We want to lessen or eliminate the chance that the user will create “bad data,” which could take two forms: “orphaned” child rows that have no parent, and child rows that are placed with the wrong parent.
  • We want the parent-child mechanism to be integrated into the existing Display Item, Edit Item, and New Item forms that SharePoint automatically generates for each list we create.

Overview

The contrived example we will describe uses the following list structure:

  • An out-of-the-box Contacts list as the parent.
  • An out-of-the-box Tasks list as the child.

There are four essential customizations that we need to make, one at the list level and three at the form level:

  1. We have set up a Lookup field on the child list to connect it to the parent. This defines the relationship at the data level and allows SharePoint to perform certain automatic functions.
  2. We have to customize the Display Item form of the parent list to show a list of the current child items owned by the parent.
  3. We have to customize the Edit Item form of the parent list to do two things: one, show a list of the current child items owned by the parent, and two, provide a link to allow the user to create a new child item, with the parent item pre-selected on the child item.
  4. We have to customize the New Item form of the child list to take care of the parent item pre-selection when the New Item form is launched from a parent item. (We do not need to customize the Edit Item form of the child list since the default dropdown list provided by SharePoint takes care of the needed functionality.)

We will be able to accomplish all of these customizations using out-of-the-box techniques that should not harm your long term SharePoint upgrade path (something we at Northridge care very passionately about). We will not be using SharePoint Designer, and this technique does not require you to customize your master page or create any custom page layouts. All of the changes you will make are stored in your content database, so they should be easy to migrate across your environments.

Getting Started

  • You will need a SharePoint 2010 website where you have basic list and page editing permissions. If you want to just follow along with this example, you can do this in your My Sites content personal site collection if this has been enabled for you.
  • You will need a document library (or some other location on the network) where you can store a JQuery text file. The permissions level and visibility of this library should be the same as the parent-child lists you will be exposing. An easy way to accomplish this is to put the library for your script in the same site (or site collection) as the parent-child lists. However, if your scenario is more complex, you might consider using a centrally stored JQuery script file that can be referenced from various sites around your farm. If you just want to follow along with this example, you may simply create a document library in the site where you are working, or use a document library you already have.
  • You will need to download a JQuery text file and place it in the aforementioned document library. Later you will embed a link to this script in some JavaScript code you will put in your list forms. The example below uses JQuery version 1.6.4. Chances are the code here will work with later versions as well, but if you have trouble getting a newer version to work, try going back to this version. It is a good idea to use a “minified” version of the library to get a smaller file.
  • You will need to create your parent and child lists. Our contrived example will use an out-of-the-box Contacts list called ParentContacts and an out-of-the-box Tasks list called ChildTasks. (Later we will make a small customization to the ChildTasks list.)

The image below (Figure 1) shows the All Site Content view for a basic site I have created in my My Sites area. I used the Blank Site template to create the site. Then I created a Document Library called SiteFiles and the aforementioned parent and child lists, ParentContacts and ChildTasks. The jquery-1.6.4.min.js text file is in the document library. At this point, I have not made any customizations, only laid the foundation.

Figure 1: The basic foundation for the example, with document library, parent list, and child list

First Customization: Lookup Field on the Child List

Something that takes a little while to get used to is which side of a parent-child relationship in SharePoint we actually modify in order to define the relationship. The answer is that it is the child list that we modify. The parent list does not include explicit fields or settings to define the relationship. Instead, we add a “Lookup” type of field to the child list, pointed to the parent list. The child defines the relationship.
Navigate to the ChildTasks list and look for the List Settings button on the ribbon. It is on the far right end of the List tab. On the List Settings page, look for the Columns area. The image below (Figure 2) shows the default columns list for our out-of-the-box Tasks list called ChildTasks.


Figure 2:
The default Columns list for the ChildTasks list, before we have added the Lookup column

In our example, we are going to click on the Create column link, but you could also choose a site column you have defined instead. Creating the column on the list directly keeps it isolated to just this list. The image below (Figure 3) shows the first section of the form to define a new column, Name and Type. We give the column the name “ParentContact,” and we choose the type Lookup.

 Figure 3: Values for the Name and Type section of the form

The image below (Figure 4) shows the second section of the form, Additional Column Settings. Some things to note from this form:

  • We have provided a Description, which is useful later, since SharePoint will display it on the New Item and Edit Item forms.
  • We are requiring a value, meaning a child Task must have a parent Contact.
  • We are not requiring unique values, since we want a parent Contact to be able to own multiple child Tasks.
  • We have chosen the ParentContacts list as the source of our Lookup value.
  • We are using the Full Name field from the parent list, which just happens to be the best value from a Contact list to show in a dropdown list on the child form. The field you choose here should be one that will help a human operator distinguish one parent in the list from another using a single value.
  • We have accepted the default “on” values for Add to all content types and Add to default view. These are generally convenient to leave on.

 Figure 4: Values for the Additional Column Settings section of the form

The image below (Figure 5) shows the final portion of the form, Relationship. In our example, we have chosen to enable relationship enforcement, which is kind of like foreign key referential integrity in a database. We have chosen to enable the Cascade delete option, which means that if a parent Contact is deleted, all of its child Tasks will be automatically deleted.

Figure 5: Values for the Relationship section of the form

The image below (Figure 6) shows the confirmation dialog you see if you decide to enable relationship enforcement. Click OK.

Figure 6: Confirmation dialog to create an indexed column, which is needed for enforcing the Lookup relationship

Figure 7 below shows the result of our work: a new ParentContact column has been added to the Columns list on the List Settings page:

Figure 7: New ParentContact column has been added to the ChildTasks list

At this point, we need to pause and create some test data. Specifically, we need a couple parent Contacts before we get into the customizations that allow us to start adding child Tasks. It is useful to define at least two or three parent items so that later you can reliably test the parent pre-selection on the child New Item form. Figure 8 shows that we have defined two test items in the ParentContacts list.

Figure 8: We have added some test data to the ParentContacts list

Switching back to the ChildTasks list, we can perform a quick test to verify that our Lookup column relationship is reflected in the ChildTasks list. The image below (Figure 9) shows the New Item form of the ChildTasks list, which comes up when we click the Add new item link on the ChildTasks list.

Figure 9: The New Item form of the ChildTasks list, showing the ParentContact dropdown from our Lookup field

This is one of three forms that SharePoint automatically generates for us when we define a new list. As we’ll see in a minute, SharePoint also allows us to modify these forms. However, so far we are just looking at the default form. Notice the ParentContact dropdown list at the bottom of the form, showing the Full Name field of the ParentContacts list.

SharePoint automatically added this dropdown to the form based on the list settings we defined above. Right now, using this default form, we can type in the details for a new ChildTask, use this dropdown list to choose a ParentContact, and save the new ChildTask. The form works. However, this dropdown is only part of what we need. Returning to the big picture, at this point we have three remaining gapsin our solution:

  • We don’t have any way to see the list of ChildTasks that a ParentContact owns.
  • We don’t have any way to create a ChildTask while we are looking at a ParentContact item. Right now the only way we have to add new ChildTasks is to navigate separately to the ChildTasks list.
  • We have a usability and data integrity problem: it is too easy for an end user to miss that ParentContact dropdown, or to make a mistake in setting it. Notice in Figure 9 that the first ParentContact in the list is automatically chosen, which is a default behavior of SharePoint. Even the most fastidious and observant user is going to make a mistake some of the time, and we’re going to have Tasks on the wrong Contacts.

We have solutions to these challenges. Keep reading…

Second Customization: Child List on Parent Display Item Form

Now we will shift our attention from the lists to the forms. As we mentioned, SharePoint automatically creates three forms when we define a new list. They are:

  • The Display Item form, which offers a read-only view of a list item.
  • The Edit Item form, which is a data entry form that appears when you click the Edit Item button on the ribbon of the Display Item form.
  • The New Item form, which is a data entry form that appears when you click the Add new item link for the list.

Assuming you have list editing permissions, you should also have the permission to edit these forms. We are not going to change any of the existing elements on the form. We will only be adding new web parts to the forms. All of our changes will be stored in the content database and should not give us any trouble with the “un-ghosting” phenomenon that harms your SharePoint upgrade compatibility.
The image below (Figure 10) shows the Modify Form Web Parts dropdown button on the ribbon of the ParentContacts list. This button is small and easy to miss, way over to the right in the List tab of the ribbon. You can edit the form of your choice by dropping down the button list and choosing one of the forms to edit. In this case we are going to choose the Default Display Form option.

Figure 10: Dropping down the Modify Form Web Parts ribbon button

When the form editor comes up, you will notice that the form is made up of a single column web part area. Notice the familiar Add a Web Part link at the top. However, we want to turn our attention to the Insert tab on the ribbon. Click the Insert tab, and you should see a Related List dropdown button. As shown below in Figure 11, because of the Lookup relationship we defined earlier between the ParentContacts and ChildTasks lists, the ChildTasks child list is available for us to insert into the form.

Figure 11: Showing the ribbon button on the Display Item form to insert a Related Items list web part for the ChildTasks

Figure 12 shows what this Related List web part looks like after it has been inserted into the bottom of the Display Item form. Keep in mind that this form will be read-only at runtime, so this list will not allow editing or adding. Later, we will be adding another Related List web part like this one to the Edit Item form.

Figure 12: The Related List web part inserted at the bottom of the Display Item form

Notice that this is a web part like any other. We could edit the web part and do things like change its title, change its Chrome setting, change the list view it is based on, etc. For our example, however, we will only make one modification: turning off the toolbar.

Edit the web part and change the Toolbar setting to “No Toolbar.” The result will look like Figure 13, below. This step is a good idea in order to reduce confusion about the “editability” of the web part on the Display Item form.

Figure 13: The same Related List web part with the toolbar turned off

At this point, we have completed the customizations to the ParentContacts Display Item form. After you close the editor for the Display Item form, return to the ParentContacts list and click on one of the test list items. You will see the Display Item form with a Related List web part at the bottom. If you have not created any ChildTasks list items yet, you may not have anything in the list. That’s OK. Our next customization will allow you to start adding ChildTasks when you are editing a ParentContact.

Third Customization: Child List and New Item Link on Parent Edit Item Form

We have to modify one more form for the ParentContacts list. Use the same Modify Form Web Parts button on the ribbon, but this time choose Default Edit Form. The Edit Item form editor will look similar to the Display Item form, but this is a data entry form, so the fields will look different than the read-only Display Item form. We won’t be changing any of the fields, however, only adding some new web parts to the bottom of the form.
We start by using the Insert menu to insert a ChildTasks Related List web part, exactly as we did in the previous step. We also want to repeat the step of turning off the toolbar, but this time for a different reason: we do not want the user to use the default “Add new item” link that is displayed when the toolbar is enabled. This is important, because the default “Add new item” link will not load our ChildTasks new item form with the current ParentContact pre-selected. As we discussed, this is an important step for data quality. We don’t want the user to have to think about setting the ParentContact dropdown on the child form.
After we have inserted the Related List at the bottom of the Edit Item form, we need to follow one additional procedure that will allow a user to add a ChildTask directly from a ParentContact. The steps are:

  1. Insert a Content Editor web part to the Edit Item form, below the Related List you just added. You may have to push the Content Editor down to the bottom yourself after it has been inserted. (Tip: sometimes it’s easier to drag the web part below upward rather than trying to drag your web part downward.)
  2. Edit the settings of the Content Editor web part and turn the Chrome Type setting to “None”.
  3. Since we have turned off the chrome, the Title of the web part will not be visible. This is good, because we don’t need the user to see a title for this web part. However, giving this web part a good title now will help future SharePoint administrators understand what we are doing here, and why we added this web part. A good title will prevent a fellow administrator from having to look inside the content editor to see what’s going on. Give it a Title value like “New Child Item Script and Link”.
  4. Click inside the Content Editor and use the Edit HTML Source button on the ribbon. This will allow you to paste raw HTML code into the web part. Copy and paste the code below.
  5. Critical step: modify the code as described below and save the Content Editor web part. (Thank you to SharePoint blogger Mark Rackley for his work on these techniques and for being the original author of the JavaScript code found in this article. See additional links at the end of this article.)

<script type=”text/javascript”>
function NewChildItem(newFormPath) {
// Get the Query String values and split them out into the vals array
var vals = new Object();
var qs = location.search.substring(1, location.search.length);
var args = qs.split(“&”);
for (var i=0; i < args.length; i++) {
var nameVal = args[i].split(“=”);
var temp = unescape(nameVal[1]).split(‘+’);
nameVal[1] = temp.join(‘ ‘);
vals[nameVal[0\]] = nameVal[1];
}
var IDColumn = vals[“ID”];
NewItem2(event, newFormPath + “?ParentID=” + IDColumn);
}
</script>
<a href=”javascript:NewChildItem(‘[YOUR-SITE-PATH]/Lists/ChildTasks/NewForm.aspx’);”>Click here to add a new Task to this Contact</a>

(Note: as attributed at the end of this article, credit is due to blogger Mark Rackley for devising the original JavaScript code on which the above code is based.)
Notice that this code is made up of two sections: a section inside a pair of SCRIPT tags and a section inside a pair of A tags. Notice that the href target of the link is the NewChildItem() function that is defined in the script block. There are some things you will want to change in this code for your purposes:

  1. You should change the name of the JavaScript function to suit your actual data scenario. The name NewChildItem() was chosen because we are using a parent Contact list and a child Task list. Choose a similar name consistent with your actual lists.
  2. You should change the path that is passed to the NewItem2() function to the actual path your child list’s NewForm.aspx page. Generally it will be in the form shown above: site URL + “/Lists/” + list name + “/NewForm.aspx”.
  3. You should customize the text inside of the A link. As you can see in Figure 14 below, this link will appear below the Related List web part. It should be something recognizable to your end users and appropriate to your data scenario. You could even create a graphical button image-based link in this spot instead of a text-based link. Just make sure your link calls that NewChildItem() function.

After you save the Content Editor web part, you will likely see a message that SharePoint modified your HTML. This is OK. SharePoint will attempt to validate and “clean up” your HTML, and there’s not much you can do about it.
The image below (Figure 14) shows the result of our efforts. We have the Related List web part without the toolbar, and we have the link to add a new item.

Figure 14: Showing the Edit Item form with the Related List web part and the link to add a new item

Don’t worry if your Related List still looks like ours: empty. In our example, we still have not created any child list items. We’re almost ready to start adding child items.

Something that may not be obvious: the way to get to this form (other than navigating directly to the EditForm.aspx url) is to first go to the Display Item form and then click on the Edit Item button in the ribbon. Until you are editing a list item, you won’t see the Edit Item form. When you are just looking at a list item, you are seeing the Display Item form.
Under the Related List, if we click the new link we created, if we did everything correctly the New Item form of the child list should come up. If you don’t see a New Item for the child list, you’re not ready to move on to the next step yet. If you do see the New Item form, that is good. Your code is probably working.
However, we’re not ready to do a full test yet. Before we can test, we need to do the final customization, as described below in the next step. The script and link we created on the ParentContacts Edit Item form will call the New Item form and pass the parent ID to the form. In the next step, we will put some code in the New Item form to accept this value and set it on the child list item.
Note: the NewItem2() function is a SharePoint 2010 client API function that brings up a modal dialog box. If you desire, you can use the following line in place of the NewItem2() line, which will navigate to the New Item form instead of using the dialog:

window.location = newFormPath + “?ParentID=” + IDColumn;

Fourth Customization: Set Parent Value on Child New Item Form

Now we are ready to put the final piece in place. We have connected the lists at the data level using a Lookup field, and we have modified the Display Item and Edit Item forms to account for the child items. Now we will modify the New Item form of the child list.
In the previous step, we made a customization to the Edit Item form of the parent list. One of the things we added was a link that made a call to the NewChildItem() function we defined using JavaScript code. What that code does is two things: first, it loads the New Item form of the child list (NewForm.aspx), and second, it passes a parameter to the form called ParentID. The JavaScript code we are about to place in the New Item form will accept this ParentID parameter and use it to pre-set the ParentContact dropdown list.
To start, navigate to the child list. In our example, this list is called ChildTasks. On the List tab of the ribbon, use the Modify Form Web Parts dropdown button to select the Default New Item form. This will load the form editor, which should by now be familiar to you. Follow these steps:

  1. Insert a Content Editor web part and push it down to the bottom of the form.
  2. Edit the settings of the web part. Under the Layout category, check the Hidden checkbox. We do not want anyone to actually see this web part. It will have JavaScript code in it, but no visual elements.
  3. Even though this web part will be invisible, it is also a good idea to change the Title of the web part to something that will be helpful to other SharePoint administrators. If you give the web part a good name, a fellow administrator will be able to tell what it is without having to look inside it. Give it a Title something like “Parent Item Preselect Script”.
  4. Click inside the Content Editor and use the Edit HTML Source button on the ribbon. This will allow you to paste raw HTML code into the web part. Copy and paste the code below. (Thanks to SharePoint blogger Mark Rackley.)
  5. Critical step: you must modify the path to point to your JQuery script file. Notice the reference to a JQuery script file at the top of the code. Recall at the beginning of this article that we created a document library and then uploaded a JQuery script file into it. Copy and paste the path to that file here.
  1. Critical step: you must modify the value of the lookupFieldDisplayName variable to match the display name of the Lookup field on your child list. In our example, we called the field ParentContact. Yours will be something different.

<script src=”[PATH-TO-YOUR-JQUERY-JS-FILE]” type=”text/javascript”></script>
<script type=”text/javascript”>
jQuery(document).ready(function($)
{
var lookupFieldDisplayName = “ParentContact”;

//get “ParentID” from Query String
var vals = new Object();
var qs = location.search.substring(1, location.search.length);
var args = qs.split(“&”);
for (var i=0; i < args.length; i++) {
var nameVal = args[i].split(“=”);
var temp = unescape(nameVal[1]).split(‘+’);
nameVal[1] = temp.join(‘ ‘);
vals[nameVal[0\]] = nameVal[1];
}
var parentID = vals[“ParentID”];
//You should customize the first parameter to match
//the display name of the Lookup field on your child list
setLookup(lookupFieldDisplayName, parentID);
});
function setLookup( fieldTitle, lookupVal)
{
//Set default value for lookups with less that 20 items
if ( $(“select[title='” +fieldTitle+ “‘]”).html() !== null)
{
$(“select[title='”+ fieldTitle +”‘]”).val(lookupVal);
}
else
{
//get the hiddent input using the “optHid” attribute of displayed Input
hiddenInput = $(“input[title='” +fieldTitle +”‘]”).attr(“optHid”);
//set value in the hidden input
$(“input[id='” +hiddenInput +”‘]”).attr(“value”,lookupVal)
//get the string of choices from the input element so we can set displayed value
choices = $(“input[title='” +fieldTitle +”‘]”).attr(“choices”);
//turn choices string into an array so we can iterate through it
choiceArray = choices.split(“|”);
//improve performance by iterating over every other entry (just look at values)
for (index = 1; index < choiceArray.length; index = index + 2)
{
if (choiceArray[index] == lookupVal){
//set the displayed input which is the PREVIOUS entry in array
$(“input[title='” +fieldTitle +”‘]”).val(choiceArray[index – 1]);
}
}
}
}</script>
Here is an example showing an actual path to a JQuery script file–in this case the minified copy of version 1.6.4:
<script src=”/YourSite/YourDocLib/YourSubfolder/jquery-1.6.4.min.js” type=”text/javascript”></script>
When you have finished with the Content Editor web part, stop editing the New Item form. Now we are done with the customizations. Let’s do a test to see if it worked.

How Do We Know It Worked?

There are three main things we want to verify:

  • Test #1: When we use the Edit Item button of an item in the parent list (which loads the Edit Item form), does the link to add a new item launch the New Item form of the child list?
  • Test #2: When we launch the New Item form of the child list from the Edit Item form of the parent list (see #1), is the correct parent list item pre-selected in the dropdown list?
  • Test #3: When we have added child items to a parent, do we see an accurate list of child items on both the Display Item and Edit Item forms of the parent list?

We will use a series of screen captures to demonstrate the results of these tests in our example.
Figure 15 below shows the starting point of Test #1. We have selected an item from the ParentContact list, and we have clicked the Edit Item button on the ribbon. The section of the form shown in Figure 15 appears at the bottom of the form in our example. The list is empty because we have not added any ChildTask items yet.

Figure 15: Showing the bottom portion of the Edit Item form of a ParentContacts list item

Figure 16 below shows where Test #1 transitions into Test #2. We have clicked on the “Click here to add a new Task to this Contact” link. The New Item form has come up for the ChildTasks list. Notice that the ParentContact dropdown has an item pre-selected. You will want to perform this test a few times with different parent items to be sure that the dropdown pre-select is working correctly. Don’t take it for granted from just one test.

Figure 16: Showing a New Item form for the ChildTasks list, with the ParentContact dropdown preselected

Figures 17 and 18 below show the results of our Test #3. The first image shows the ChildTasks items owned by our ParentContact on the Display Item form. The second image shows the same on the Edit Item form.

Figure 17: A populated child list on the read only Display Item form

Figure 18: A populated child list on the read only Edit Item form

Now that was simple, wasn’t it?

Final Note

Giving credit where it is due, the following blog posts by blogger Mark Rackley should be credited for this assisting this author in putting together the above-described technique and code. The technique described in the article above synthesizes and refines the techniques described in the following two posts.
Post One
Post Two
The second post provided above is really the one that makes it work, by demonstrating the technique using a Lookup dropdown. The first post lays out the basic approach, but using a plain “ID” text field, which does not address the need/preference to use a Lookup to drive the parent-child list-to-list relationship. The second post adds the additional script that we put in the New Item form of the child list and includes special logic to handle the modified dropdown list you get when you have more than 20 parent items. (We strongly recommend you test it with a number of list items and relationships that will be realistic to your production scenario.) Mark Rackley also let us know about a third post on the parent-child topic, which you may find useful.

Thoughts on “How to Make Parent-Child Lists and Forms in SharePoint 2010”

  1. I am trying to implement this and I have a few questions – what exactly am I downloading and saving to the document library for JQuery? When I look at downloads on their site I only see .js files, no text files?
    Also, when trying to edit the HTML source in the New Item Form customization for the parent list, I can’t seem to get it right – when I customize the text inside the “A” link Sharepoint changes it and it ends up looking like this (and subsequently not working):
    >Click here to add a new Task to this Contact
    instead of this:
    Click here to add a new Task to this Contact
    I also can’t figure out from your instructions where to change the path that is passed to the NewItem2 function. Do I change that path at the beginning in the paretheses by NewChildItem, do I declare a variable called newFormPath?

  2. Hi Jessica,
    Unfortunately, Dan is no longer with the company. I’ll try to see if there is someone else that can answer your question and will get back to you.
    Thanks!
    Callie

  3. Dan’s instructions are correct, but perhaps worded a bit strangely. By “You will need to download a JQuery text file…” Dan means to say that the user needs to go download the latest version of jQuery which is a JavaScript file with a “.js” extension. He uses the term “text file” only to mean that the content (the script) is text not that the file is itself a text file (with the traditional “.txt” extension). The easiest way to get a copy of the latest version of jQuery is to visit the site (http://jquery.com/), click the large download button on the right, and then save off the file. The file may open in a new tab in the browser; if so, simply use the browser’s File menu to “Save page as…” and save off the “.js” file so that it may be uploaded to a document library during a subsequent step in Dan’s guide.
    The presence of the “>” character has me thinking that the anchor tag is somehow malformed. Be aware that a direct copy and paste from the blog post could result in some erroneous characters. For example, quotes (double and single) don’t always copy and paste well. Refer to below:
    <a href=“javascript:NewChildItem(‘[YOUR-SITE-PATH]/Lists/ChildTasks/NewForm.aspx’);” rel="nofollow">Click here to add a new Task to this Contact</a>
    <a href="javascript:NewChildItem('[YOUR-SITE-PATH]/Lists/ChildTasks/NewForm.aspx');" rel="nofollow">Click here to add a new Task to this Contact</a>
    The top line was a direct copy and paste from the blog post into Notepad. The bottom line is a correctly formatted version using standard quotes that I manually created. See the difference? The double and single quotes are different; the JavaScript within the Content Editor web part should use the lower line’s quotation convention.
    The newFormPath parameter of the NewChildItem function does not need to be declared as it is a parameter. Note the structure of the anchor tag’s href:
    “…NewChildItem(‘[YOUR-SITE-PATH]/Lists/ChildTasks/NewForm.aspx’);…”
    In this case we are essentially calling the NewChildItem function and passing the string “[YOUR-SITE-PATH]/Lists/ChildTasks/NewForm.aspx” as the newFormPath parameter. In other words, within the function body itself newFormPath is equal to “[YOUR-SITE-PATH]/Lists/ChildTasks/NewForm.aspx”
    Clicking the link should simply execute the NewChildItem function.

  4. Jessica Dominguez

    Okay, I went through the code by hand to ensure the characters were correct and used your corrected NewChildItem function in my script. So what I have now is this:

    jQuery(document).ready(function($)
    {
    var lookupFieldDisplayName = "ParentContact";
    //get "ParentID" from Query String
    var vals = new Object();
    var qs = location.search.substring(1, location.search.length);
    var args = qs.split("&");
    for (var i=0; i < args.length; i++) {
    var nameVal = args[i].split("=");
    var temp = unescape(nameVal[1]).split('+');
    nameVal[1] = temp.join(' ');
    vals[nameVal[0\]] = nameVal[1];
    }
    var parentID = vals["ParentID"];
    //You should customize the first parameter to match
    //the display name of the Lookup field on your child list
    setLookup(lookupFieldDisplayName, parentID);
    });
    function setLookup( fieldTitle, lookupVal)
    {
    //Set default value for lookups with less that 20 items
    if ( $("select[title='" +fieldTitle+ "']").html() !== null)
    {
    $("select[title='"+ fieldTitle +"']").val(lookupVal);
    }
    else
    {
    //get the hiddent input using the “optHid” attribute of displayed Input
    hiddenInput = $("input[title='" +fieldTitle +"']").attr("optHid");
    //set value in the hidden input
    $("input[id='" +hiddenInput +"']").attr("value",lookupVal)
    //get the string of choices from the input element so we can set displayed value
    choices = $("input[title='" +fieldTitle +"']").attr("choices");
    //turn choices string into an array so we can iterate through it
    choiceArray = choices.split("|");
    //improve performance by iterating over every other entry (just look at values)
    for (index = 1; index < choiceArray.length; index = index + 2)
    {
    if (choiceArray[index] == lookupVal){
    //set the displayed input which is the PREVIOUS entry in array
    $("input[title='" +fieldTitle +"']").val(choiceArray[index - 1]);
    }
    }
    }
    }

    And when I click on “Click here to add a new Task to this Contact” the link it goes to is javascript:NewChildItem('http://intranet/Lists/IT_ProjectTasks/NewForm.aspx’); but nothing happens at all.

  5. Jessica,
    The script in your last comment looks correct. Here are a couple of things to check:
    1. When you say “…the link it goes to…” do you mean that the anchor tag’s href attribute is set to “javascript:…;” or that your browser physically redirects you to another page when you click the link? The latter shouldn’t happen as the link doesn’t point to a page but rather a JavaScript function. Assuming you aren’t redirected, it sounds like there may a JavaScript error somewhere such that the function silently fails.
    2. Be sure that you’ve included a reference to the jQuery “.js” file above your script. The jQuery library must be loaded before that script block can execute (because is uses jQuery).
    <script src="[PATH-TO-YOUR-JQUERY-JS-FILE]" type="text/javascript"></script>
    <!-- then the rest of the code -->

    3. Verify that “ParentContact” is the display name of your Lookup field. If your particular field is called something else, update the following line of code accordingly:
    var lookupFieldDisplayName = "ParentContact";
    4. Check to see if there are any JavaScript errors reported by the browser after you click the link and then work to correct any issues you find. In Internet Explorer you can usually use the F12 key to access the developer tools. In Firefox, most developers prefer to use Firebug which, after the add-on is installed, is also accessible via F12 in Firefox. Chrome developer tools are built in and can also be accessed via F12. Using these developers tools you should be able to determine if there any JavaScript errors logged to the console. From there you’ll be able to start debugging the script.

  6. I have gotten every step to work on my SharePoint site, however, when I click on the add a new task link, it doesn’t default the ParentID on the new task. I’ve downloaded and directed the jquery correctly (Downloaded the compressed, production jQuery 3.1.0). The code I’m using in my Hidden Webpart is:
    jQuery(document).ready(function($)
    {
    var lookupFieldDisplayName = “ParentTicket”;
    //get “ParentID” from Query String
    var vals = new Object();
    var qs = location.search.substring(1, location.search.length);
    var args = qs.split(“&”);
    for (var i=0; i < args.length; i++) {
    var nameVal = args[i].split("=");
    var temp = unescape(nameVal[1]).split('+');
    nameVal[1] = temp.join(' ');
    vals[nameVal[0\]] = nameVal[1];
    }
    var parentID = vals["ParentID"];
    //You should customize the first parameter to match
    //the display name of the Lookup field on your child list
    setLookup(lookupFieldDisplayName, ParentID);
    });
    function setLookup( fieldTitle, lookupVal)
    {
    //Set default value for lookups with less that 20 items
    if ( $("select[title='" +fieldTitle+ "']").html() !== null)
    {
    $("select[title='"+ fieldTitle +"']").val(lookupVal);
    }
    else
    {
    //get the hidden input using the "optHid" attribute of displayed Input
    hiddenInput = $("input[title='" +fieldTitle +"']").attr("optHid");
    //set value in the hidden input
    $("input[id='" +hiddenInput +"']").attr("value",lookupVal)
    //get the string of choices from the input element so we can set displayed value
    choices = $("input[title='" +fieldTitle +"']").attr("choices");
    //turn choices string into an array so we can iterate through it
    choiceArray = choices.split("|");
    //improve performance by iterating over every other entry (just look at values)
    for (index = 1; index < choiceArray.length; index = index + 2)
    {
    if (choiceArray[index] == lookupVal){
    //set the displayed input which is the PREVIOUS entry in array
    $("input[title='" +fieldTitle +"']").val(choiceArray[index – 1]);
    }
    }
    }
    }
    Any suggestions?

  7. Hi All,
    I tried to implement this on my sharepoint. However, its working fine until I customize the list form through InfoPath? Can someone help me what do I need to do in this case

  8. I know this is old, but I too was having a problem with the click here to create… Link. I figured out that there is a problem in the code that was posted.
    vals[nameVal[0\]] = nameVal[1];
    Should actually be vals[nameVal[0]] = nameVal[1];
    The backslash was preventing the link to open. Once I corrected that the link opens when clicked.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow Us
TwitterLinkedinFacebookYoutubeInstagram