Identify content type to execute content type specific code

In another post i received a request on how to identify the content type in NewForm to execute “content type specific code”. Here’s a quick description of one method.

The method relies on a script, init_fields(), which loops trough all fields in the form and makes an object of all table rows and their HTML. This way all fields can be addressed by their FieldInternalName, returning the full HTML of that field.

The function init_fields() is a modified version of Erucy’s function for finding fields in a SharePoint form. My modified version uses FieldInternalName rather than DisplayName to locate the fields.

As always we start like this:
Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a sub site named “test” with a sub site named “English” with a document library named “Javascript”):
IMG

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

The code below uses the FieldInternalName of a specific field to ensure that the field is rendered – if so – it executes the code wrapped in that “if-statement”. The field used to identify the ContentType must reside only in that content type.

Add a CEWP belowit is essential that it is placed below – your list-form as briefly described here, and add this code:

<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
fields = init_fields();
/*
 This example shows how you can check what ContentType is used by checking if
 a field you know is in that specific ContentType is rendered
*/

// Check if the field with FieldInternalName of "OnlyInContentType1" is rendered
if(fields['OnlyInContentType1']!=undefined){
	alert("This is content type nr 1");
	// Execute any code that addresses the first content type
}

// Check if the field with FieldInternalName of "OnlyInContentType2" is rendered
if(fields['OnlyInContentType2']!=undefined){
	alert("This is content type nr 2");
	// Execute any code that addresses the second content type
}

function init_fields(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf('FieldInternalName="')<0) return; 
var start = $(this).html().indexOf('FieldInternalName="')+19;
var stopp = $(this).html().indexOf('FieldType="')-7; 
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
}
</script>

The code above does work in NewForm, DispForm and EditForm.

To get the “FriendlyName” of the content type in DispForm or EditForm you can use the script below. This script also enables you to hide the “Content type selector” from EditForm.

<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

// This example shows how you can get the "FriendlyName" of the ContentType
// You can optionally hide the "ContentType selector from EditForm"

// Get the name and hide the selector
var contentType = getContentFriendlyNameOptionalHide(true);
alert(contentType);

function getContentFriendlyNameOptionalHide(hide){
if(hide){
	$("select[id$='ContentTypeChoice']").parents('tr:first').hide();
}
	// EditForm
	var value = $("select[id$='ContentTypeChoice']").find('option:selected').text();
	// DispForm
	if(value==''){
		value = $("span[id$='InitContentType']").text();
	}
return value;
}
</script>

Ask if something is unclear.

Regards
Alexander

16 thoughts on “Identify content type to execute content type specific code”

  1. Hi Alexander,
    I am trying to link what you’ve demonstrated in “Convert Singleline textfield to filtered lookup dropdown” with the info in this post and have got myself discombulated. I have a document library with multiple content types. Some have both a ToCompany and a FromCompany single line text column, some have just one of the columns, and some have neither. From your other post, I added two CEWP to the EditForm page to get the lookup dropdown, one for the ToCompany and the other for the FromCompany. It works fine if the content type has both columns. You pointed me to this post for assistance on making it work with all Content Types. I gather I need to add another CEWP with a variation of the code above to see if one, both, or neither column exists then execute additional code to enable or disable the other CEWP? Can you offer some more assistance to get me rolling again? thanks.

    1. Hi,
      You use the code example in the topmost codeblock above. Refer all the scripts as you did in the “Convert Singleline textfield to filtered lookup dropdown-code” in the top.

      Then insert the CEWP-code from the “Convert Singleline textfield to filtered lookup dropdown” where the alerts are found in the code above (line 11 and 17).

      Alexander

  2. Hi Alexander,
    Here is my attempt at what you advise – I know I’ve mucked it up somewhere, as some fragments of the script appear on the editform page and the dropdowns only appear when both the To and From Company columns exist. Can you see where I’ve gone awry (and yeah, java is a foreign language to me)? thanks

    fields = init_fields();
    if(fields[‘To_x0020_Company’]!=undefined)
    {
    if(fields[‘From_x0020_Company’]!=undefined)
    {

    fields = init_fieldInternalName();
    singleFilteredDropdown(‘{A2982A31-5208-4FE5-B620-C0C159235F12}’,L_Menu_BaseUrl,’Title’,’Created’,’Boolean’,’Neq’,”,false,’DropdownNr1′,”,’To_x0020_Company’,true,false,false);
    singleFilteredDropdown(‘{A2982A31-5208-4FE5-B620-C0C159235F12}’,L_Menu_BaseUrl,’Title’,’Created’,’Boolean’,’Neq’,”,false,’DropdownNr2′,”,’From_x0020_Company’,true,false,false);

    }
    else
    {

    fields = init_fieldInternalName();
    singleFilteredDropdown(‘{A2982A31-5208-4FE5-B620-C0C159235F12}’,L_Menu_BaseUrl,’Title’,’Created’,’Boolean’,’Neq’,”,false,’DropdownNr1′,”,’To_x0020_Company’,true,false,false);

    }
    }
    else if (fields[‘From_x0020_Company’]!=undefined)
    {

    fields = init_fieldInternalName();
    singleFilteredDropdown(‘{A2982A31-5208-4FE5-B620-C0C159235F12}’,L_Menu_BaseUrl,’Title’,’Created’,’Boolean’,’Neq’,”,false,’DropdownNr2′,”,’From_x0020_Company’,true,false,false);

    }
    else
    {

    }

    function init_fields(){
    var res = {};
    $(“td.ms-formbody”).each(function(){
    if($(this).html().indexOf(‘FieldInternalName=”‘)<0) return;
    var start = $(this).html().indexOf('FieldInternalName="')+19;
    var stopp = $(this).html().indexOf('FieldType="')-7;
    var nm = $(this).html().substring(start,stopp);
    res[nm] = this.parentNode;
    });
    return res;
    }

    1. Try this:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      // Make "object" from all fields in the form
      fields = init_fields();
      
      // If field "To_x0020_Company" is present
      if(fields['To_x0020_Company']!=undefined){
      	singleFilteredDropdown('{A2982A31-5208-4FE5-B620-C0C159235F12}',L_Menu_BaseUrl,'Title','Created','Boolean','Neq','',false,'DropdownNr1','','To_x0020_Company',true,false,false);
      }
      // If field "From_x0020_Company" is present
      if(fields['From_x0020_Company']!=undefined){
      	singleFilteredDropdown('{A2982A31-5208-4FE5-B620-C0C159235F12}',L_Menu_BaseUrl,'Title','Created','Boolean','Neq','',false,'DropdownNr2','','From_x0020_Company',true,false,false); 
      }
      
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return; 
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7; 
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      </script>
      

      Alexander

  3. thanks again. the above didn’t quite work but following your logic I added back in the

    from the dropdown post between lines 1 and 2 above which did the trick. By the way, feel free to add the suffix “The Great” to your name.

    1. Sorry – my fault to not refer the scripts… I wrote it in notepad – didn’t test it. Glad you figured it out.

      By the way – to post code – use this format – just replace “(” and “)” with “[” and “]”:
      (sourcecode language=”javascript”)
      …code here…
      (/sourcecode)

      Alexander

  4. I have successfully implemented this, but I am having a small issue. One content type uses your arrFieldsToAccumulate and the other does not. when I set the arrFieldsToAccumulate function up to run in the one content type, I get an error in the other when I try and save the data. the error is
    arrFieldsToAccumulate is undefined. I have tried adding this script to both content type and hiding the fields as opposed to firing the event by content type still no success.

    any suggestions?

    1. I figured out a workaround. Not sure if this would be the proper way to fix it, But I added the arrFieldsToAccumulate and function to all content type if statements. In the CT that did not use this script I added it like this

      arrFieldsToAccumulate = [];
      addAccumulateFunctionOnLoad();
      

      in the CT that did use the script added like designed

      arrFieldsToAccumulate = ['TowersSupported|Towers_Supported','GateKeeper|Gatekeepers'];
      addAccumulateFunctionOnLoad();
      

      hope this is helpful.

    2. This has to do with the function “PreSaveAction()” located in the file “AccumulateSelectionsToMultilineText.js”.

      You can modify this function to check the content type and only to execute the code if the correct content type is used.

      However, your method of overcoming the error is sufficient, but it would be enough just to define the variable
      arrFieldsToAccumulate = [];
      to overcome this issue, no need to call the function
      addAccumulateFunctionOnLoad();
      from the content type where the fields are not present.

      Alexander

  5. Hello-quick question. I am trying execute some client side jquery code for all folders in a SharePoint 2010 view. Will your solution above work in a CEWP on the default view page for Content type = “Folder”?

    thx
    Bill

  6. Hi,
    This article is 7 years old so I’m fairly sure it will NOT work.

    I’m not sure what you mean with “view” – are you trying to add code to a form (NewForm, DispForm or EditForm) or in a list view?

    In case it is a form, you should look at DFFS

    Alexander

  7. Hi, so I am trying to hide, remove, or disable the ECB context menu for folders only in a specific 2010 document library in the AllItems.aspx default view. Do you have any ideas on how to accomplish this. I am currently using jquery window.location.href.index of and checking all the possible urls. This works but if a new folder is added, then I must update the file. I would like to be able to check for the content type = folder and set it there. Any ideas would be much appreciated.

    Thx
    Bill

Leave a Reply

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