0

I am using sp2013. I have custom list with 4 custom contenttype. I would like to implement some clientside code. If a user create a new item you need to select the contenttype. All contenttypes have the title field. I would like to add the contenttype name in the title field after changing the contenttype.

var contenttypename = [javascript logic]

if(contenttypename == 'CTA')
{
    [javascript logic to set the title column realtime]
}
4

Since you are using SharePoint 2013, below is demonstrated how to customize New Form page via Client-Side Rendering (CSR) in order to set default Title field value based on Content Type name.

Rendering template file listing: setting default Title field value based on Content Type name

(function () {


    function initTitleDefaultValue(renderCtx) {
       var ctName = renderCtx.CurrentItem.ContentType;  //get current Content Type  
       // set default value for a Title field
       renderCtx.CurrentFieldValue = ctName;
       return SPFieldText_Edit(renderCtx); //default renderer for Text field  
    }


    function registerRenderer()
    {
      var ctxForm = {};
      ctxForm.Templates = {};
      ctxForm.Templates.Fields = {
          'Title' : { 'NewForm': initTitleDefaultValue }
      };

      SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctxForm);
    } 
    ExecuteOrDelayUntilScriptLoaded(registerRenderer, 'clienttemplates.js');

})();

Steps

Save the specified template file as formtemplate.js and upload it into Site Assets Library.

Then, specify the JSLink property. Navigate to your list, and in the ribbon select ‘Form Web Parts > Default New Form’. This opens the New Form in edit mode.

enter image description here

Edit the web part, and expand “Miscellaneous”. Under JS Link, add the link to the JS file which you just created:

~site/SiteAssets/formtemplate.js

Results

I have a Custom List named Phones with several Content Types enabled. When the new item is being created for a Content Type named Samsung Phone, the New Form displays as shown below

enter image description here

where Manufacturer is a display name for Title field.

  • the code of "Vadim Gremyachev" works for me, but i just need the content type without setting it in a textfield. is this possible? i guess its not that easy because renderctx is used. – stluis Aug 26 '15 at 6:35
3

Here is an example:

var listItem = null;
var listContentTypes = null;

function getContentTypeOfCurrentItem(id) {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle("Projects");

    //get the list item and load() it
    listItem = oList.getItemById(id);
    clientContext.load(listItem);

    //get the content types and load the collection
    listContentTypes = oList.get_contentTypes();
    clientContext.load(listContentTypes);

    clientContext.executeQueryAsync(Function.createDelegate(this, getContentTypeOfCurrentItemSucceeded), Function.createDelegate(this, onQueryFailed));
}

//the callback
function getContentTypeOfCurrentItemSucceeded(sender, args) {    
    var ctid = listItem.get_item("ContentTypeId").toString();

    var ct_enumerator = listContentTypes.getEnumerator();
    while (ct_enumerator.moveNext()) {
        var ct = ct_enumerator.get_current();

        if (ct.get_id().toString() == ctid) {
            //we've got our content type, now let's get its name
            var contentTypeName = ct.get_name();
        }
    }
}

Source: http://derekgusoff.wordpress.com/2012/10/09/working-with-content-types-in-the-javascript-client-object-model/

UPDATE Add a CEWP or Script Editor webpart(SP 2013) in the edit form and use following JS code to change the title field based on the value of Content Type:

<script src="/SiteAssets/jquery-1.7.1.min.js"></script>
<script language="javascript" type="text/javascript">
var contentTypeField = null;
$(document).ready( function() {
    var contentTypeField = $("select[title='Content Type']");   
    $("input[Title='Title']").val(contentTypeField.val());
    contentTypeField.change(function () {        
        $("input[Title='Title']").val(contentTypeField.val());
    }); 
  });

The script assumes that there that JQuery is present in SiteAssets library. When an edit form is loaded it reads the value in Content Type field and sets the title field. It then attaches change event to the Content Type field and sets the title field based on changed content type.

Note:I haven't tested the script.

  • Requesting the person who down voted to give the reason in comments section. – Nadeem Yousuf Mar 21 '14 at 15:00
  • 1
    The OP's question is poorly worded, but I think he wants to grab the CT name from the Form, not through a query. +1 for the blog reference though! – Derek Gusoff Mar 21 '14 at 19:40
  • 2
    This only works for edit form, and not for new form where you don't have an id yet. – Mikael Svenson Feb 18 '16 at 11:48
0

This is now i did it,

    var context,
        listItems,
        listName = "Projects",
        list,
        camlQuery;


    function getProjectsFromList() {
        try {
            context = new SP.ClientContext.get_current();
            list = context.get_web().get_lists().getByTitle(listName);
            camlQuery = new SP.CamlQuery();

    var camlString =
    "<View>" +
        "<Query>" +
            "<Where>" +
                "<Eq>" +
                    "<FieldRef Name='ProjectId' />" +
                    "<Value Type='Text'>" + empId + "</Value>" +
                "</Eq>" +
            "</Where>" +
            "<OrderBy>" +
                "<FieldRef Name='Year' Ascending='FALSE' />" +                  
            "</OrderBy>" +
        "</Query>" +            
    "</View>";

            camlQuery.set_viewXml(camlString);

            listItems = list.getItems(camlQuery);

            context.load(listItems, "Include(Id,Title,ContentType)");
            context.executeQueryAsync(onSuccessGetProjectsFromList, onFail);
        }
        catch (err) {
            alert("OnLoad Error: " + err);
        }
    }

    function onSuccessGetProjectsFromList() {
        if (listItems.get_count() != null && listItems.get_count() > 0) {

            var listEnumerator = listItems.getEnumerator();

            while (listEnumerator.moveNext()) {
                var item = listEnumerator.get_current();
                var cType = item.get_contentType().get_name();
            }       
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.