How to use these scripts in a customized form

03.08.2010 Updated the article with another example on how to build the fields-object in a customized form.


This article describes how to use most of the solutions found in this blog with a customized form. The scripts which this article addresses, is the ones involving the function “init_fields()_v2”.

This was originally an answer to a comment in one of the articles.


I get this question a lot:
How can i use these scripts in a customized form?

The answer is simple, but i will explain it so that you understand why it’s not working.

This script relays in the function init_fields() to identify and “objectify” the form by it’s <TR> tags (table rows). What the function does is to find all the FieldInternalNames in the code by this “information-tag”:
[javascript]
<!– FieldName="This is the DisplayName"
FieldInternalName="ThisIsTheFieldInternalName"
FieldType="SPFieldText"
–>
[/javascript]
It then make an object which, when called with the FieldInternalName of a field, returns an object containing that table row (both formlabel and formtable).

When initiated like this:
[javascript]
fields = init_fields_v2();
[/javascript]
You address a <TR> like this:
[javascript]
$(fields[FieldInternalName])
[/javascript]
Where “FieldInternalName” is the FieldInternalName of your field. Read here how to identify the FieldInternalName.

This is the original function for use in standard SharePoint forms:
[javascript]
function init_fields_v2(){
var res = {};
$("td.ms-formbody").each(function(){
var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);
if(myMatch!=null){
// Display name
var disp = myMatch[1];
// FieldInternalName
var fin = myMatch[2];
// FieldType
var type = myMatch[3];
if(type==’SPFieldNote’){
if($(this).find(‘script’).length>0){
type=type+"_HTML";
}
}
if(type==’SPFieldLookup’){
if($(this).find(‘input’).length>0){
type=type+"_Input";
}
}
// Build object
res[fin] = this.parentNode;
res[fin].FieldDispName = disp;
res[fin].FieldType = type;
}
});
return res;
}
[/javascript]

Customized form

When you modify the list form in SharePoint Designer, you loose the FieldInternalName and therefore the function init_fields_v2() does not return anything.

To address the fields on a custom form you have to find another way of addressing these fields and to “objectify” them in the same way as the script init_fields_v2(). Basically you could insert some kind of “identifier-attribute” on the <TR> tags, or you can go with the displayName – only remember that if you change the displayName – you have to update your script…

To use the a custom made ID attribute, replace the init_fields_v2() function with this one:
[javascript]
function init_fields_v2(){
var res = {};
$("td.ms-formlabel").each(function(){
var thisID = $(this).attr(‘id’);
res[thisID] = $(this).parents(‘tr:first’);
});
return res;
}
[/javascript]

This approach requires that you add a unique ID attribute to the <TD> holding the formlabel. Here is an example of code from a customized form:
[javascript]
<table border="0" cellspacing="0" width="100%">
<tr>
<td width="190px" valign="top" class="ms-formlabel" id="TitleColumnCustomID">
<H3 class="ms-standardheader">
<nobr>Title<span class="ms-formvalidation"> *</span>
</nobr>
</H3>
</td>
<td width="400px" valign="top" class="ms-formbody">
<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’)}"/>
<SharePoint:FieldDescription runat="server" id="ff1description{$Pos}" FieldName="Title" ControlMode="New"/>
</td>
</tr>
<tr>
<td width="190px" valign="top" class="ms-formlabel" id="ChoiceColumnCustomID">
<H3 class="ms-standardheader">
<nobr>MyChoiceColumn</nobr>
</H3>
</td>
<td width="400px" valign="top" class="ms-formbody">
<SharePoint:FormField runat="server" id="ff2{$Pos}" ControlMode="New" FieldName="MyChoiceColumn" __designer:bind="{ddwrt:DataBind(‘i’,concat(‘ff2′,$Pos),’Value’,’ValueChanged’,’ID’,ddwrt:EscapeDelims(string(@ID)),’@MyChoiceColumn’)}"/>
<SharePoint:FieldDescription runat="server" id="ff2description{$Pos}" FieldName="MyChoiceColumn" ControlMode="New"/>
</td>
</tr>
</table>
[/javascript]
Note the id attributes “TitleColumnCustomID” and “ChoiceColumnCustomID” in line 03 and 15.

To “get” the Title field you address it like this:
[javascript]
fields = init_fields_v2();
var myTitleField = $(fields[‘TitleColumnCustomID’]);
alert(myTitleField.html());
[/javascript]

Ask if anything is unclear.

Regards
Alexander

53 thoughts on “How to use these scripts in a customized form”

    1. This article is a description of how the solutions in all the other articles can be adapted to a customized form. This article is “nothing” by it selves.

      Alexander

  1. Hi Alex

    What if I copied over the section below for each field on form would your original script still work…is it the position or is it that it just doesn’t know the names of the fields…

    Because if it is just that it doesn’t know and is location independent it is easier and more practical to copy over the filed internal names etc….

    Wouldn’t that be a cleaner way of doing it?

    Tony

  2. I apologize alex, this section is what I am refering to with the appriopriate tags replaced currently with [].

    Here is what I am thinking if I am stupid again sorry….

    I would copy over all the tags below place it in one section in page and use it…would that work or is it that we need it next to the specific td tags….

    To me that is minimal work and keep the integrity of your script…..:-)

    [!– FieldName=”Title”
    FieldInternalName=”Title”
    FieldType=”SPFieldText”
    –]

    1. Tony, did this method finally work for you?
      SharePoint seems to ignore the comment info with FieldInternalName (not displayed anymore in browser form source…)

  3. I use this an my sharepoint site but not work. please write me detail steps.
    I opened my site in sharepoint designer then open the list form and hide this default NewForm.aspx. then i insert custome list form of that form, and add CEWP where i write this JS. but not it works.
    i mention here, in default page(new, edit, display) this JS works fine.
    Plesr reply me as early as possible.

    thanking you,
    Riaz

    1. Hi,
      I’m afraid i can’t give you any detailed steps other than the ones described in the above article. When you modify the form, it’s only you who know how the form layout are, and it’s impossible for me to help without having the code for your form.

      Be sure to put the CEWP containing the script below the new customized form and above the original form if it’s still in the page.

      Alexander

  4. Hi Alex,
    I have got the word count script working with the default NewForm.aspx
    Now I am moving onto getting it to work via a custom form. I am not a proper coder and just wanted to be pointed in the right direction since I do find it difficult to understand the explanation above. Is there another example of this working in a custom form or is there a sample site I could be pointed to?

  5. Working like a charm! Thank you!

    Unfortunately, my source list has 10K rows, so it needs a lot of time to be loaded. I have to look for something that makes it happen faster.

  6. Hi Alex,

    I’m bit confusing. I created Custom List Form. I’m having 4 columns (i.e., Title, Second Column, Third Column and Fourth Column).

    I create ID for each like CustomTitle, CustomSecondColumn, CustomThirdColumn, CustomFourthColumn).

    Questions :

    1. In the “arrOfFields” — what names I should Use ?

    2. It is better if we have clear example link Standard SharePoint Forms.
    Possible plz try to explain with an code example what we had in below link …
    http://spjsblog.com/2009/12/19/accordion-in-sharepoint-form

    Thanks,
    Rao…

    1. Hi,
      You would have to replace the function init_fields_v2() from the “accordion-code”with the one from this article. The fieldNames is the ones you listed above – your custom ID’s.

      Alexander

      1. Hi,
        Unfortunately this is now so easy. If you have opted to modify your form in SPD, it is impossible for me to know how you have modified it. The code provided in this page is just a general guide to how you (possibly) can adapt your already customized form to support some of my solutions.

        Please keep in mind that ALL my solutions are made for 100% unmodified forms.

        Alexander

  7. Hi,

    I am using sharepoint Offic Designer 2007, to validate a checkbox(terms and conditions) thru javacsript.

    Details:

    I have created a custom list and in the custom there is a field called terms and conditions. I have inserted the custom list in new .aspx page. I have changed the sharepoint checkbox to asp checkbox.

    And I am trying to validate it through client validation function by aspx custom validator. My code looks like

    function TermsValidate(sender, args)

    { args.Isvalid=documnent.getelementById(“ff2_1”).checked); }

    The validation looks like it triggering but object required error comes up.

    Alexander, could you kindly try this for me!

    Thanks

    1. Sorry, but i cannot help you with this. All my “work” in SharePoint forms is done in the standard, unmodified forms. When customizing the form it is very difficult to be of any help as each and every form is different. If you want to do this in a SharePoint standard form using javascript, i might be able to help. If you want to go this path, please post in the request thread

      Alexander

  8. Hello Alexander,

    I can get your script working with out any issues on a NewForm and EditForm but I can’t get it to work in a custom form made in SP Designer. I tried pasting your code that you provided on top but I keep getting the error ‘ff1{$Pos}’ is not a valid identifier. Last question will it be possible to use the ASP.NET controls so I can use the autopostback?

  9. Hello Alex,

    I almost have it working because I am no longer getting any javascript errors. The only issue I am having right now is that all my textboxes are invisible. I can’t see any fields in my form that are suppose to turn into dropdown menus.

  10. Hello Alex,

    Sorry for all the posting! I got it working! I was using the class ms-vb instead of ms-formbody and that is the reason nothing was showing up. Last question I promise, what I am trying to accomplish is every time a user makes a selection in the dropdown my dfwp filters out the information with either a query string a control. Any suggestions?

    1. Hi,
      Because of my delayed answer you figured it out yourself!

      Is this related to the cascading dropdown script?

      Could you describe a bit more what you want to happen when you do the selections – and if it has to be “onchange”. Could it be done upon save?

      Please post it in the article it is related to.

      Alexander

  11. Hi Alex,

    This needs to be done “onchange”. I do not have a save button. I will describe you what my form needs to do. When the user selects “Canada” I want my dataformwebpart to load all textbooks from Canada. When the user selects “Ontario” I need my dataformwebpart to show textbooks from the country Canada and the province Ontario. I have three dropdowns, Country, Province and City. This works great with the ASP.NET controls because I can do a AutoPostBack but I do not have the option to do the cascading dropdown with the ASP.NET controls.

  12. I have yet found away to get your scripts to work, in our systems.
    It seems they just do not execute and have no clue as to why.
    this last one I attempted Dynamic expand/collapse fields or array of fields, display as a normal sharepoint forms newform, displayform, editform.
    Followed every step and reverified so many times its driving me insane.
    I performed a viwe source and according to your instructions I should find displayname this does not exist in any of my forms, I also looked at some other forms not related to your script and again it does not show displayname in the view source.
    Any Ideas? Please.

  13. hi alex,

    i’ve tried implement ur script, n follow step by step what u had explained here..but i’m always get null result when try to : rt(myTitleField.html()); …. i’m using spd 2010, n download jquery-1.5.1.min.js… i’d download and add all reference , any suggestions ??? …thanks

  14. I am not new to sharepoint but some projects come up where it requires me to expand my abilities.
    I have been using the other example of your script for sometime yet now they require me to use this one or one like it.
    So here is my question
    I have replaced the section in the existing code with
    function init_fields_v2(){
    var res = {};
    $(“td.ms-formlabel”).each(function(){
    var thisID = $(this).attr(‘id’);
    res[thisID] = $(this).parents(‘tr:first’);
    });
    return res;
    }
    ]]>

    but for the life of me I cannot figure out what else I am supposed to do with your script do I change the script in any other way like change fieldinternalname to field name or what?
    I compared your example to my form and in some cases it does look the same but cannot find this ID i am supposed to use and where do I put it in your script?

    Thanks any help is great help.

    1. Hi,
      Which script is it you are trying out? – this article is just an example on how to use any of my “field interaction solutions” with a customized (in sharePoint Designer) form.

      Alexander

  15. Hi,

    Very useful scripts. I got it working on the defualt forms. But my custom newform it is not working. I think I’m almost there.

    1)I have placed this function in my customTabForm.js. (removed default one)

    function init_fields_v2(){
    var res = {};
    $(“td.ms-formlabel”).each(function(){
    var thisID = $(this).attr(‘id’);
    res[thisID] = $(this).parents(‘tr:first’);
    });
    return res;
    }

    2) I added custom Id to the ‘s formlabel. Example:

    3) I added the following to the CEWP:

    fields = init_fields_v2();
    var myCompanyField = $(fields[‘CompanyNameCustomID’]);
    alert(myTitleField.html());

    4) Updated Tabconstructor fields in CEWP

    {name:’First Tab’,fields:[‘MyCompanyField’],mouseOver:’This is the first tab’,tabStyle:”},

    5) I get the alert that shows the code for the ‘s formlabel and formbody returned.

    6) Then the page shows with no tabs just the form in full showing.

    Am I missing something? I wasn’t sure if need to change code in number 1 above. I am not very familiar with JQuery syntax.

    Thanks.

  16. Hi again,

    My example for #2 was missing:

    2) I added custom Id to the ‘s formlabel.

    Example: class=”ms-formlabel” id=”CompanyNameCustomID”

    FYI: This is to custom the Tabs in Forms scripts.

    Thanks.

    1. Hi,
      The jQuery team has changed “prop” and “attr” handling since 1.6.2.

      Try changing
      var thisID = $(this).attr(‘id’);

      to

      var thisID = this.id;

      In your init_fields – script (or revert back to v1.6.2)

      Alexander

  17. Hi again,

    Changed to v 1.6.2 and still not working. Looks like throws an attr null or not object error on the following line in the SelectTab function

    tId = $(elm).attr(‘id’).substring(4);

    -Janet

    1. Hi,
      Sorry for the late reply. This is the exact same problem as described in my comment above. Replace:

      tId = $(elm).attr(‘id’).substring(4);

      with

      tId = elm.id.substring(4);

      Alexander

  18. Hi Alexander,

    Thanks for all your time and effort for all of these.

    I’m having problems using setFieldValue in a custom form. It looks for a FieldType that is not set in your modified init_fields_v2() above. It will be very much appreciated if you can provide how to set a lookup field for custom form.

    Thanks a lot!

    1. Hi,
      I’m afraid it would be nearly impossible to tell when we are talking about a customized form. There is no way I can know how the form looks when it’s customized so I’m afraid the little info given in this article is all I can give without looking at the form in question.

      It’s not my field, but when you first have customized the form using SharePoint Designer, you may as well find a “SharePoint Designer” solution and not a JavaScript solution to the problem.

      Alexander

  19. Got this working with the standard forms no problem but cant for the life of me get it working with custom forms.

    I have created a new list with only 3 columns, all text…
    Replaced init_fields in the tabsforsharepointforms.js with:

    function init_fields_v2(){
    var res = {};
    $(“td.ms-formlabel”).each(function(){
    var thisID = $(this).attr(‘id’);
    res[thisID] = $(this).parents(‘tr:first’);
    });
    return res;
    }

    Added tabconstructor CEWP above hidden webpart and below my custom dataformwebpart

    Set custom ids like this:

    Title

    Everything looks right but all I get is the 2.4 copyright link on the form and no tabs… cant see anything wrong

      1. Hi, Do a search in the code you are using to ensure that there are no other copies of the original init_fields function – I have added this function to some of the scripts in the past so you might have more then one.

        If you find any other copies – remove them to ensure the correct one is being used.

        Alexander

  20. Hi Alexander I hope you can help explain how I can stop the error in the editform here as everything else is fantastic using your hide fields in forms script!

    I get the error “Request Date and Time 21/06/2012 02:10 null”
    and I get the error “Store Unknown fieldType: SPFieldTaxonomyFieldType, please ensure you use the function init_fields_v2().I have read the above notes about init_fields but I am a newby and don’t know where to put this code. How do I amend your wonderful hide fields script to do this?

  21. Hi Alex,

    Great code! I just wanted to leave a comment about using customized forms. I found a workaround without modifying your code!

    What I did was
    1. Make a copy (I am using SharePoint Designer) of the list form I want to apply the accordion effect to.

    2. Rename it to whatever you want and save it whereever you want (I have a folder for customized forms in my application).

    3. Detach the copied form from the MasterPage if necessry and make any design changes you need. (I did this in my case because I needed to embed my form in a page along with other custom forms and didn’t want the Site chrome to show.)

    4. Append the accordion code to the page.

    Happy coding everyone! 🙂

  22. Hey, Alex – awesome stuff here, thanks. You talk about adding the cascading drop list scripts to a custom form here. I’m trying your Dynamic Forms for SP, so can I add the cascading droplist functionality to that? Forgive me if it’s already there & I haven’t seen it; I’m kinda new at this stuff. Thanks – Brett

  23. Hi Alex,
    Can you please suggest how I can go with the displayName of the fields, as you mentioned.
    I have modified the form and that’s why lost the field internal names.
    I want to make this work with field Display Names
    Pls help

    1. I have the same issue, You happened to find any solution to use display name instead of Internal name?

      Everything was working fine in 2007 environment but, only Lookup fields are not displayed anymore after migrating to 2013 using a migration tool.

      Later i found this is because the internal names are changed only for lookup columns. They are still not displayed even after i changed with the new internal names such as “‘Test%5Fx0020%5Ftest”

Leave a Reply