Thursday, April 4, 2013

Getting and setting SharePoint form field values

Forms Designer provides JavaScript-framework that allows to manipulate fields in a simple JQuery manner. You can find how to set or get current field values in the official website.

But what if the field is more complex than a simple input, what if it has multiple parts of values, like lookup or date and time? How do you get lookup id and lookup text? Below I placed the table that illustrates how you get or set different value types for the most SharePoint types of fields. To create this table I used the current last version of Forms Designer: 2.7.9.

Field Type Get / Set Script
Single Line of Text Get
fd.field('Title').value();
Set
fd.field('Title').value('Default title');
OnChange
fd.field('Title').change(function(){});
Multiline Plain Text Field Get
fd.field('MultipleLinePlain').value();
Set
fd.field('MultipleLinePlain')
  .value('MultipleLinePlain');
OnChange
fd.field('MultilinePlain').change(
  function(){alert('Field has been changed!')}
);
Multiline RTF Field Get
fd.field('MultilineRichText').value();
Set
fd.field('MultilineRichText')
  .value('MultilineRichText');
OnChange
fd.field('MultilineRichText').change(
  function(){alert('Field has been changed!')}
);
Multiline Enhanced Rich Text Field Get
fd.field('MultilineEnhanced').value();
Set
fd.field('MultilineEnhanced')
  .value('MultilineEnhanced');
OnChange
fd.field('MultilineEnhanced').change(
  function(){alert('Field has been changed!')}
);
Choice Single Get
fd.field('ChoiceSingle').value();
Set
fd.field('ChoiceSingle').value('B');
OnChange
fd.field('Choice').change(function(){
  alert('Field changed!');
});
Choice Multiple Get
var checkboxIndex = 2;
fd.field('MultiChoice').control()._el()
  .find('input[type="checkbox"]').eq(checkboxIndex)
  .is(':checked');
Set
var checkboxIndex = 2;
fd.field('MultiChoice').control()._el()
  .find('input[type="checkbox"]').eq(checkboxIndex)
  .prop('checked', true);
OnChange
fd.field('MultiChoice').change(function(){
  alert('Field changed!');
});
Number Get
fd.field('Number').value();
Set
fd.field('Number').value('13');
OnChange
fd.field('Number').change(function(){
  alert('Field changed!');
});
Currency Get
fd.field('Currency').value();
Set
fd.field('Currency').value('23');
OnChange
fd.field('Currency').change(function(){
  alert('Field changed!');
});
Date Get
fd.field('Date').value();
Get Date-object
field('Date').control('getDate') // returns Date-object
Set
fd.field('Date').value('4/21/2012'); // by String

fd.field('DateTime')
  .value(new Date()); // by Date-object
OnChange
fd.field('Date').change(function(){
  alert('Field changed!');
});
DateTime Get
fd.field('DateTime').value()[0]; // date
fd.field('DateTime').value()[1]; // hours
fd.field('DateTime').value()[2]; // minutes
Get Date-object
field('DateTime').control('getDate') // returns Date-object
Set
fd.field('DateTime')
  .value(['4/21/2012', '11 PM', '35']); // by Array
fd.field('DateTime')
  .value(new Date()); // by Date-object
OnChange
fd.field('DateTime').change(function(){
  alert('Field changed!');
});
Hyperlink / Image Get
fd.field('Hyperlink').value()[0]; // link
fd.field('Hyperlink').value()[1]; // descr
Set
fd.field('Hyperlink')
  .value(['http://someurl', 'description']);
OnChange
fd.field('Hyperlink').change(function() {
  alert('Changed!');
});
Single Lookup Value
Get Text
fd.field('Lookup').control('getSelectedText');
Get ID
fd.field('Lookup').value();
Set Text
fd.field('Lookup').value('Text');
Set ID
var ID = 4;
fd.field('Lookup').value(ID);
OnChange
fd.field('Lookup')
  .change(function(){});
Multi Lookup Values Get All
var selectedItems = fd.field('LookupMultiple')
  .control()._el().find("select:eq(1) option");
var s = '';
for (var i = 0; i < selectedItems.length; i++) {
  s += selectedItems.eq(i).text() + ';';
}
alert(s);
Get First
fd.field('MultiLookup').control()._el()
  .find("select:eq(1) option").eq(0).text()
Get Second
fd.field('MultiLookup').control()._el()
  .find("select:eq(1) option").eq(1).text()
Get ID
// first selected:
fd.field('MultiLookup').control()._el()
  .find('select:eq(1) option').eq(0).val(); 

// second selected:
fd.field('MultiLookup').control()._el()
  .find('select:eq(1) option').eq(1).val(); 
Set
var ID = 3;
// select element by ID:
fd.field('MultiLookup').control()._el()
  .find('select:eq(0)').val(ID); 

// add button click:
fd.field('MultiLookup').control()._el()
  .find('button:eq(0)').click(); 
OnChange
fd.field('MultiLookup').change(function(){
  alert('Field changed!');
});
Boolean Get
fd.field('Boolean').value();
Set
fd.field('Boolean').value('1');
OnChange
fd.field('Boolean').change(function(){
  alert('Field changed!');
});
Client People Picker Get All Logins
fd.field('User').control('ready', function() {
  var selectedUsers = fd.field('User').value();
  for (var i = 0; i < selectedUsers.length; i++) {
    alert('Login: ' + selectedUsers[i].Key);
  }
});
Set
// assign value by a display name
fd.field('User').value('Tim Watts');

// by a login
fd.field('User').value('DEV\\ann');

// or by an e-mail:
fd.field('User').value('AGibson@contoso.com');
  
OnChange
fd.field('User').change(function(){
  alert('Field changed!');
});
Server People Picker with multiple choice Get All Logins
var logins = '';
$.each(fd.field('People').value()
  .dictionaryEntries,
  function() {
    logins += this.AccountName + '; ';
  });
Set
fd.field('People').value('DOMAIN\\login');
OnChange
fd.field('People').change(function(){
  alert('Field changed!');
});
Server People Picker with single choice Get
fd.field('PersonGroupSingle')
  .value().dictionaryEntries[0].AccountName
Set
fd.field('Person').value('DOMAIN\\login');
OnChange
fd.field('Person').change(function(){
  alert('Field changed!');
});
External Data Get

Returns field value of External List item:

fd.field('ExternalData').value()
  .dictionaryEntries[0]['FieldOfExternalList']
'ExternalData' is an internal name of the lookup column.
'FieldNameOfExternalList' is an internal name of the external list column.

If you include additional columns to the target list in lookup settings you will be able to get them dynamically as well:

fd.field('ExternalData').value()
  .dictionaryEntries[0]['AdditionalFieldOfExternalList']
'AdditionalFieldOfExternalList' is an internal name of the external list column which has been added as additional field in lookup settings.

Set

fd.field('ExternalData')
  .value({key: '__bg40003300', text: 'Item 1'});
key is BDC Identity of the selected item.
text is a display name of the selected item.

OnChange
fd.field('ExternalData').change(function(){
  alert('Field changed!');
});
Plumsail Cross-site Lookup with single value Get ID
fd.field('CrossSiteLookup').value()
Get title
fd.field('CrossSiteLookup').control('data')['Title']
Set

Set ID:

fd.field('CrossSiteLookup').value(1);

Set ID and display text:

fd.field('CrossSiteLookup')
  .value({Id: 1, Title: 'Item 1'});

OnChange
fd.field('CrossSiteLookup').change(function(){
  alert('Field changed!');
});
Plumsail Cross-site Lookup with multiple values Get IDs Returns an array if selected ids:
fd.field('CrossSiteLookup').value()
Get titles

First item:

fd.field('CrossSiteLookup').control('data')[0]['Title']

Second item:

fd.field('CrossSiteLookup').control('data')[1]['Title']

Set
fd.field('CrossSiteLookup')
  .value([{Id: 1, Title: 'Item 1'}, 
    {Id: 2, Title: 'Item 2'}])

OnChange
fd.field('CrossSiteLookup').change(function(){
  alert('Field changed!');
});

37 comments:

  1. Replies
    1. fd is the base variable of the Forms Designer's JavaScript framework. We also recorded a video to demonstrate how to use it.

      Delete
  2. HI,

    How to get the fd value? above code through the error "fd is undefined"

    Thanks,
    Parthiban

    ReplyDelete
    Replies
    1. Hello Parthiban,

      fd variable is a part of Forms Designer's JavaScript framework. So, to use it you have to design form with Forms Designer and put your js-code into built-in JS-editor.

      Delete
  3. Hello,
    For single look up field to get the text:
    Get Text
    fd.field('Lookup').control('getSelectedText'); What is the value in 'getSelectedText' in the control?
    Thanks,
    Kat

    ReplyDelete
    Replies
    1. Hello Kat,
      That is the way to get the display text of the selected item instead of its ID.

      Delete
  4. Hi
    In order to set the enhanced richtext multi line field "Description" to the text "TestText" I have added a button with the on click script :
    fd.field('Description').control()._el()
    .find('.ms-rtelong').contents()
    .find('body').html('TestText);
    But i does not work, any suggestions?
    (the button worked fine on a plain sigle line field with the corresponding syntax)


    ReplyDelete
    Replies
    1. Hello Glad,
      As described in the table above, you should use the following code to set the value of the enhanced rich text field:
      fd.field('Description').control()._el().find('div.ms-rtestate-write').html('TestText');

      Delete
  5. Sorry, but I'll try over again because I can't get it to work.
    In Sharepoint 2010 I have defined a field in a list "Description" and its type is "Rich text (Bold, italics, text alignment, hyperlinks)" - multiline - 6lines
    In FormsDesigner I have added the field "Description" to a form and also a Button where I have all the scripts above. What would be the correct script for the button to assign the text "Hello" to the field "Description"?

    ReplyDelete
    Replies
    1. If you use Rich text (not Enhanced rich text), you should use the following code:

      fd.field('Description').control()._el()
      .find('.ms-rtelong').contents()
      .find('body').html('new value');

      Make sure that 'Description' is the internal name of your field.

      Delete
    2. Hi again. Is "Description" a reserved name as a field? I tried your code and it works if I create a new field say "RTXT" but if I name the field "Description" its not possible to write to it.

      Delete
  6. undefined error when i use fd.field

    ReplyDelete
  7. i tried for singleline and as well for date column

    ReplyDelete
  8. Hello, is there a way to force the refresh of a calculated field?

    ReplyDelete
    Replies
    1. Hello Lucila,
      Do you mean you need to refresh the calculated field on the edit form dynamically without refreshing the page? Unfortunately, this is impossible, but you can perform the calculation and put the result onto your form with the help of custom JavaScript code. Does it make sense?

      Delete
  9. Hello Dmitry,

    How I can concatenate multiple choices fields in one text filed?
    like in InfoPath?

    ReplyDelete
    Replies
    1. Hello Keti,

      You can concatenate them with the help of our JS-framework in a form following way:
      fd.field('FullName').value(fd.field('LastName').value() + ', ' + fd.field('FirstName').value())

      Or you can create a calculated column and use CONCATENATE function in its formula:
      =CONCATENATE([Column1]," sold ",[Column2]," units.")
      http://msdn.microsoft.com/en-us/library/office/bb862071(v=office.14).aspx

      Delete
  10. Hello Dmitry,

    How can I one date field based on another? For example, how can I use Forms Designer to fill in Evaluation Date to be 3 months after Closed Date when a Closed Date is selected? Thanks in advance.

    ReplyDelete
    Replies
    1. Hi,
      Please, use the code below. Do not forget to replace the internal names with your values:

      function setEvaluationDate() {
      if (fd.field('Closed').value()) {
      var parts = fd.field('Closed').value().split('/');

      var date = new Date(parts[2], parts[0] - 1, parts[1]);
      date.setMonth(date.getMonth() + 3);

      fd.field('Evaluation').value((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
      }
      }

      fd.field('Closed').change(setEvaluationDate);

      Delete
    2. Hi Dmitry,

      Thanks! That works perfectly.

      Delete
  11. Hi Dmitry Kozlov,
    I'm using Multi Choice field in my form,On change event is not working.

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Hi Dmitry,

    Does the Choice Single apply to radio button type Choice fields as well? Thanks in advance.

    ReplyDelete
    Replies
    1. Hi,
      Yes, you can use the same code for ribbon buttons but please, note that fd.field('Choice').value() returns the selected index instead of the text.

      Delete
  14. Hi Dimitry,

    I want to get the text of a lookup column, and set it as the text in a external data column, here is what I have but doesnt work:
    var text = fd.field('Color').control('getSelectedText');
    fd.field('ColorRef')
    .value({key: '2642ad57-60ab-44a7-90d8-f424cdcf0bad', var text });

    Any ideas?

    ReplyDelete
  15. To add to this - if your field name has spaces, remember the old SharePoint Trick - spaces are replaced by _x0020_ (same as other special characters that don't go well inside of URLs - they get replaced by their ASCii code, in that format)

    ReplyDelete
  16. Hi,
    How can Get the selected text of radio button choice field?
    fd.field('ResponsibleUnit').Value() returns the selected index value. I need selected text

    ReplyDelete
    Replies
    1. Hi,
      Try the following code:
      fd.field('ResponsibleUnit').control()._el().find(':checked').parent().text()

      Delete
  17. Hi Dmitry,
    I have another doubt regarding accordion.

    By default when I click new form , The first accordion tab will be expanded. I want to collapse every tab on New form and need to expand only when I clicked the tab. how can I resolve this?
    I added this on Page load
    $('#fd_accordion-0 > h3:eq(0)').click()

    But its not working

    ReplyDelete
  18. Also I set Accordion mode as Multiple. That too not working. the first tab is Expanded

    ReplyDelete
    Replies
    1. Open the designer, select the Accordion, and clear the Expanded property. Then clear cookies. Please, ask other questions that do not relate to getting/settings fields in our forum.

      Delete
  19. Hello, how can i get the value of a managed metatdata field in spforms
    thank you

    ReplyDelete
  20. Hello I have dropdown on grid column and i need to set specific text on other column based on dropdown value section. but i did not able to get any change event for dropdown within Grid.

    ReplyDelete
  21. Hello,

    I have a field which type says is unknown. That field is of type Artfulbits Cascade Lookup field. Problem is the Change event is not working, so I would like to know if there is something on SPForms side that I can do. I need the change event to be fired to execute a query.

    ReplyDelete
  22. Hi, Can we change single line of text field into dropdown using spform js framework?

    ReplyDelete

Note: Only a member of this blog may post a comment.