Search code examples
sharepointformscode-behind

Reference custom list form fields from code behind and automatically fill them with values


I`v made my custom NewForm.aspx for my list and I want to add some custom code to it. So I inherit that form from my own class:

public class MyCustomNewForm : Microsoft.SharePoint.WebPartPages.WebPartPage

Now I want to reference some of available fields to automatically fill them for user. (Javascript won't help here as I have to get some data from other lists).

But I have no idea how do I reference these fields from codebehind files.

The code for control field is written (well, it was generated by Sharepoint Designer when using command Insert > SharePoint Controls > Custom List Form...) in .aspx page like this:

<SharePoint:FormField runat="server" id="ff1{$Pos}" ControlMode="New" FieldName="Title" __designer:bind="{ddwrt:DataBind('i',concat('ff1',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Title')}"/>

When looking at id at runtime, it is insanely long

alt text http://img33.imageshack.us/img33/7495/ss20090713143352.png

So how do i reference fields, so I could set Text property on them in my codebehind file?


Solution

  • #Dont mind this painful solution, but scroll down to see edit. Uhh, I`v found a workaround. But warning! if you don't need to use any Sharepoint objects to access any values dynamically, then this post is not for you, instead, you would like to read some of the referenced articles.

    So, to pre-fill some fields in a NewForm.aspx with values from some other list, do the following.

    In short:

    1. Make your custom list item form. Do it step-by-step.

    2. Make a class that inherits from Microsoft.SharePoint.WebPartPages.WebPartPage

    3. Inherit that class on your custom form aspx <%@ Page. Mine looks like this: Inherits="xx.MeetingWorkspace.Tasks_NewFormxx, xx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5"

    4. In protected override void OnInit(EventArgs e) function use FindControlRecursively to find a ContentPlaceHolder object with ID "PlaceHolderMain" (Call that function on this.Controls[0], not on this object).

    5. Make HtmlHiddenField objects, assign values and add attribute "Title" using method HtmlHiddenField.Attributes.Add(). You will need that for step 7.

    6. Add hidden fields to the ContentPlaceHolder you got previously.

    7. Use Javascript (read here or here) to fill your desired fields from hidden field values to those fields that user sees.

    P.S. I'm beginner at sharepoint so better use these steps with caution. I'd be glad to find out an answer where you can reference your fields in code, so I don't have to use any javascript stuff.

    My journey in long: As I mentioned, I inherited my own public class for this form. With this technique it should be possible to reference existing form field by declaring these class controls with a variable name as same as form ID. In screenshot I have a TextBox class object with ID ctl00_PlaceHolderMain_g_77625.... etc.

    Now, in my class I tried making a variable with the same name as ID, but it does not initialize and the value is null. I thought maybe ID is being changed, I checked, but no, it stays as it was before.

    So I tried using Control.FindControl, but it does not search recursively, so I found this article: Recursive Page.FindControl. (You would probably want to read some comments, as there are better implementations with generics). Important: Read comment "Sam on August 2, 2008 4:13 AM" before using FindControlRecursive method.

    So, with the function in hand, I passed the ID as argument - still no luck, it just returns null for me. Luckily, I could pass PlaceHolderMain as ID and it would return me main placeholder object.

    So the workaround would then be on the overriden method OnInit(EventArgs) make HtmlHiddenField objects, set their values to whatever you want and add those hidden fields to PlaceHolderMain . (ContentPlaceHolder.Controls.Add())

    Then with some javascript on ASPX page I was able to load values from hidden fields to my preffered fields (well I found a way to reference the fields I want with javascript. Two useful articles for this: shorter one and longer one)

    #Edit: Less painful solution Ohh, glad i found this. With jPoint (jQuery for SharePoint) and then with some script you can use querystring parameters to prepopulate list fields.

    <script type="text/javascript" src="//sharejpoint.googlecode.com/files/jPointLoader-0.6-expanded.js" ></script>
    <script>  
      $(document).ready(function() {
        jP.Form.readForm();
        $.each(jP.Form.Items, function (idx, item) {
        if(querySt(item.Name) != null && querySt(item.Name) != "undefined")
          jP.Form[item.Name].val(unescape(querySt(item.Name)));
        });
       });
    
    //Gets value of querystring key
    function querySt(ji)
    {
          hu = window.location.search.substring(1);
          gy = hu.split("&");
          for (i=0;i<gy.length;i++)
          {
                  ft = gy[i].split("=");
                  if (ft[0].toUpperCase() == ji.toUpperCase()) //Fixed query so it is case insensitive
                  {
                          return ft[1];
                  }
          }
    }
    </script>
    

    This script can be found in comments in this article.