Sharepoint client object model: How to get all the fields in a list - sharepoint

I have a list named "Discussions List". I want to bring all columns from the list.
I want to know how to do it SharePoint Client Object Model.

OK. Found the solution. Answer Here using a list I'm getting by title, but will work with any method:
// Get your ClientContext for your site in 'clientContext'
SP.List oList = clientContext.Web.Lists.GetByTitle("List Title Here");
SP.FieldCollection fieldColl = oList.Fields;
clientContext.Load(fieldColl);
clientContext.ExecuteQuery();
foreach (SP.Field fieldTemp in fieldColl)
{
MessageBox.Show(fieldTemp.InternalName.ToString()); //I used MessageBox to show, but you can do whatever you like with it here.
}

Bingo. You're going to love this. Thank goodness for generics and Linq!
// return all rows and (selected) fields of a list--fields are included dynamically
private Dictionary<string,Dictionary<string,object>> getListData( ClientContext ctx )
{
Log.LogMessage( "Fetching {0}{1}", ctx.Url, ListName );
var list = ctx.Web.Lists.GetByTitle( ListName );
// fetch the fields from this list
FieldCollection fields = list.Fields;
ctx.Load( fields );
ctx.ExecuteQuery();
// dynamically build a list of fields to get from this list
var columns = new List<string> { "ID" }; // always include the ID field
foreach( var f in fields )
{
// Log.LogMessage( "\t\t{0}: {1} of type {2}", f.Title, f.InternalName, f.FieldTypeKind );
if( f.InternalName.StartsWith( "_" ) || f.InternalName.StartsWith( "ows" ) ) continue; // skip these
if( f.FieldTypeKind == FieldType.Text ) // get Text fields only... but you can get other types too by uncommenting below
// || f.FieldTypeKind == FieldType.Counter
// || f.FieldTypeKind == FieldType.User
// || f.FieldTypeKind == FieldType.Integer
// || f.FieldTypeKind == FieldType.Number
// || f.FieldTypeKind == FieldType.DateTime
// || f.FieldTypeKind == FieldType.Lookup
// || f.FieldTypeKind == FieldType.Computed
// || f.FieldTypeKind == FieldType.Boolean )
{
columns.Add( f.InternalName );
}
}
// build the include expression of which fields to fetch
List<Expression<Func<ListItemCollection, object>>> allIncludes = new List<Expression<Func<ListItemCollection, object>>>();
foreach( var c in columns )
{
// Log.LogMessage( "Fetching column {0}", c );
allIncludes.Add( items => items.Include( item => item[ c ] ) );
}
// get all the items in the list with the fields
ListItemCollection listItems = list.GetItems( CamlQuery.CreateAllItemsQuery() );
ctx.Load( listItems, allIncludes.ToArray() );
ctx.ExecuteQuery();
var sd = listItems.ToDictionary( k => k["Title"] as string, v => v.FieldValues ); // FieldValues is a Dictionary<string,object>
// show the fields
foreach( var i in sd.Keys )
{
Log.LogMessage( "\tItem: {0}", i );
foreach( var c in columns )
{
Log.LogMessage( "\t\t{0}: {1}", c, sd[ i ][ c ] );
}
}
return sd;
}

Related

Calculate the sum of a specific array data

After calling all the data from my database, I would like to try and calculate the individual values of my array. I have made 2 users state as "banned"
//get all banned status for all users
res.data.data.forEach((dataItem, index) => {
console.log(`Banned ${index}`, dataItem.banned);
I would like to try and get the sum of "banned" and "not banned" which in this case is "banned 2" and "NotBanned 2"
tried this but dint work
for (const dataItem of res.data.data) {
let NotBanned = 0;
if(dataItem.banned === false){
NotBanned++;
console.log("Not Banned", NotBanned);
}
}
for (const dataItem of res.data.data) {
var BannedUsers = 0;
if(dataItem.banned === true){
BannedUsers++;
console.log("Not Banned",BannedUsers);
}
}
let
bannedUsers = 0,
unBannedUsers = 0;
const response = res.data.data
for(let users = 0; users < response.length; users ++ ) {
if(!response.banned) {
unBannedUsers += users;
}
else {
bannedUsers += users;
}
}
console.log(`Banned Users : ${bannedUsers} , UnBanned Users : ${unBannedUsers}` )

Fields except Id and Tile are NULL

I'm facing a problem, all fields except ID, Title, Created, etc.. are Null, so all custom columns won't load any value.
I Tried to load the ListItems with Include, but result is still the same.
What am I doing wrong?
var participants = Spo.GetParticipants(true);
var oList = Ctx.Web.Lists.GetByTitle("Participant");
var camlQuery = new CamlQuery
{
ViewXml = "<ViewScope='RecursiveAll'><RowLimit>5000</RowLimit></View>"
};
var listItems = oList.GetItems(camlQuery);
//Ctx.Load(listItems,
// items => items.Include(
// item => item["ID"],
// item => item["Title"],
// item => item["Email"],
// item => item["FirstName"],
// item => item["Company"],
// item => item["Phone"],
// item => item["Street"],
// item => item["ZipCode"],
// item => item["City"]), items => items.ListItemCollectionPosition);
Ctx.Load(oList);
Ctx.Load(listItems);
Ctx.ExecuteQuery();
foreach (var oListItem in listItems)
{
foreach (var it in participants)
{
if (oListItem != null && oListItem["Email"].ToString() == it.Email)
{
oListItem["FirstName"] = it.FirstName;
oListItem["LastName"] = it.LastName;
oListItem["Company"] = it.Company;
oListItem["Phone"] = it.Phone;
oListItem["Street"] = it.Street;
oListItem["ZipCode"] = it.ZipCode;
oListItem["City"] = GetLookupCity(it.City);
//FieldLookupValue lv = new FieldLookupValue();
//lv.LookupId = int.Parse() it.City
p = "UPDATED: " + it.Email;
}
else
{
}
}
}
There should be something wrong with camlquery. There should be blank between View and Scope
<View Scope='RecursiveAll'><RowLimit>5000</RowLimit></View>

Conflict in a FileDownload control in Notes 9 XPage

I am using this code placed in beforeRenderResponse event of an XPage in a notes 8.5.3 application:
function overrideFileDownloadAction( fDownload ){
if( fDownload === null )
return;
rekOverrideFileDownloadAction( fDownload, fDownload );
}
function rekOverrideFileDownloadAction( component:javax.faces.component.UIOutput, fDownload:com.ibm.xsp.component.UIFileDownload ){
try{
var children:java.util.List = component.getChildren();
var it:java.util.Iterator = children.iterator();
var curChild:javax.faces.component.UIOutput;
while( it.hasNext() ){
curChild = it.next();
if( typeof( curChild ) === 'com.ibm.xsp.component.xp.XspEventHandler' ){
var group = new com.ibm.xsp.actions.ActionGroup();
var list = new java.util.ArrayList();
group.setComponent( fDownload );
list.add( curChild.getAction() );
list.add( mBinding );
group.setActions( list );
curChild.setAction(group);
}
rekOverrideFileDownloadAction( curChild , fDownload );
}
}catch(e){}
}
viewScope.flag_remove = false;
var code = "#{javascript:var fileDownload1:com.ibm.xsp.component.xp.XspFileDownload = getComponent('fileDownload1');var index = fileDownload1.getRowIndex(); if(viewScope.flag_remove == false){viewScope.types.removeElementAt(index); viewScope.flag_remove = true}}";
var mBinding = facesContext.getApplication().createMethodBinding(code, null );
overrideFileDownloadAction( getComponent( 'fileDownload1' ) );
I use this in order to save some info together with the file (i.e i have a drop down to select the type of file that i upload). So i want this info to be deleted and added together with the uploaded file.
I found the code above by googling and it works normally.
Now i installed Notes 9 and i want to test my app for potential issues.
I get this error:
com.ibm.xsp.actions.ActionGroup incompatible with
com.ibm.xsp.actions.DeleteAttachmentsAction
when switching a document to edit mode.
Does anyone have the same problem? Any solutions?

CakePHP Issue with Search and Pagination

I have a problem with my CakePhp Site.
My index is showing fine with pagination, but when I search the page, pagination is gone and the search results aren't showing (instead the index is showing without paging).
Any idea where my code is wrong?
class ItemsController extends AppController {
var $name = 'Items';
// load any helpers used in the views
var $helpers = array('Paginator', 'Html', 'Form', 'Javascript', 'Misc', 'Time', 'Tagcloud');
var $components = array('RequestHandler');
/**
* index()
* main index page for items
* url: /items/index
*/
function index() {
// get all options for form
$tags = $this->Item->Tag->find('list', array(
'fields'=>'id, name',
'order'=>'Tag.name',
'conditions'=> array(
'Tag.status'=>'1'
)
));
// add name to option
$tags = array(''=>'Tags') + $tags;
//pr($tags);
// if form submitted
if (!empty($this->data)) {
// if reset button pressed redirect to index page
if(isset($this->data['reset'])) {
$this->redirect(array('action'=>'index'));
}
// init
$url = '';
// remove search key if not set
if($this->data['search'] == '') {
unset($this->data['search']);
}
// loop through filters
foreach($this->data as $key=>$filter) {
// ignore submit button
if($key != 'filter') {
// init
$selected = '';
switch($key) {
case 'tag':
$selected = $tags[$filter];
break;
case 'search':
$selected = $filter;
break;
}
// if filter value is not empty
if(!empty($filter)) {
$selected = $this->slug($selected);
$url .= "/$key/$selected";
}
}
}
// redirect
$this->redirect('/items/index/'.$url);
} else {
// set form options
$this->data['tag'] = '';
$this->data['search'] = '';
}
// if any parameters have been passed
if(!empty($this->params['pass'])) {
// only select active items
$conditions = array('Item.status'=>1);
// get params
$params = $this->params['pass'];
// loop
foreach($params as $key=>$param) {
// get the filter value
if(isset($params[$key+1])) {
$value = $params[$key+1];
}
// switch on param
switch($param)
{
case 'tag':
// get tag
$tag = $this->Item->Tag->find('first', array(
'recursive' => 0,
'conditions' => array(
'Tag.slug'=>$value
)
));
// save value for form
$this->data['tag'] = $tag['Tag']['id'];
break;
case 'search':
// setup like clause
$conditions['Item.name LIKE'] = "%{$value}%";
// save search string for form
$this->data['search'] = str_replace('_', ' ', $value);
break;
}
}
//pr($conditions);
// get all items with param conditions
$items = $this->Item->find('all', array(
'order' => 'Item.name',
'conditions' => $conditions
));
// if tag filter has been set
if(isset($tag)) {
// loop through items
foreach($items as $key=>$item) {
// init
$found = FALSE;
// loop through tags
foreach($item['Tag'] as $k=>$g) {
// if the tag id matches the filter tag no need to continue
if($g['id'] == $tag['Tag']['id']) {
$found = TRUE;
break;
}
}
// if the tag was not found in items
if(!$found) {
// remove from list
unset($items[$key]);
}
}
}
} else {
// get all items from database where status = 1, order by name
$items = $this->Item->find('all', array(
'order' => 'Item.name',
'conditions' => array(
'Item.status'=>1
)
));
}
$this->paginate = array(
'limit' => 10
);
$data = $this->paginate('Item');
// set page title
$this->pageTitle = 'Index Page';
// set layout file
$this->layout = 'index';
// save the items in a variable for the view
$this->set(compact('data', 'tags', 'items'));
}
You'll want to pass your search conditions to the paginate functionality. You do this through the controller's paginate property.
function index() {
...
switch($param) {
...
case 'search':
$this->paginate['conditions']['Item.name LIKE'] = "%{$value}%";
More information on setting up pagination can be found here.

Dropdown field - first item should be blank - For more than one field (Sharepoint)

I was looking for a solution to the problem of getting a blank default when using a lookup in a field in Sharepoint. Kit Menke's solution to "Dropdown field - first item should be blank" question works perfectly for my first field with a lookup. But I can't make it work if have more that one field in the same list where I need to insert a blank for each lookup field (works only for the first field). I tried adding a new "Web Part" and applying the same code to the second field, but doesn't work. Any ideas? Thanks in advance
Follow-up to my answer here: Dropdown field - first item should be blank
Version 2.0 allows you to add the names of your dropdowns to dropdownNames in the MyCustomExecuteFunction function. As with the first one, this will work only with required single select lookup fields. Also, in order to edit the page again and update your Content Editor Web Part you may have to choose a value for your dropdowns otherwise you get the dreaded An unexpected error has occurred.. Good luck! :D
<script type="text/javascript">
function GetDropdownByTitle(title) {
var dropdowns = document.getElementsByTagName('select');
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns[i].title === title) {
return dropdowns[i];
}
}
return null;
}
function GetOKButtons() {
var inputs = document.getElementsByTagName('input');
var len = inputs.length;
var okButtons = [];
for (var i = 0; i < len; i++) {
if (inputs[i].type && inputs[i].type.toLowerCase() === 'button' &&
inputs[i].id && inputs[i].id.indexOf('diidIOSaveItem') >= 0) {
okButtons.push(inputs[i]);
}
}
return okButtons;
}
function AddValueToDropdown(oDropdown, text, value, optionnumber){
var options = oDropdown.options;
var option = document.createElement('OPTION');
option.appendChild(document.createTextNode(text));
option.setAttribute('value',value);
if (typeof(optionnumber) == 'number' && options[optionnumber]) {
oDropdown.insertBefore(option,options[optionnumber]);
}
else {
oDropdown.appendChild(option);
}
oDropdown.options.selectedIndex = 0;
}
function WrapClickEvent(element, newFunction) {
var clickFunc = element.onclick;
element.onclick = function(event){
if (newFunction()) {
clickFunc();
}
};
}
function MyCustomExecuteFunction() {
// **** ADD YOUR REQUIRED SINGLE SELECT FIELDS HERE ***
var dropdownNames = [
'Large Lookup Field',
'My Dropdown Field'
];
var dropdownElements = [];
for (var d = 0; d < dropdownNames.length; d++) {
// find the dropdown
var dropdown = GetDropdownByTitle(dropdownNames[d]);
// comment this IF block out if you don't want an error displayed
// when the dropdown can't be found
if (null === dropdown) {
alert('Unable to get dropdown named ' + dropdownNames[d]);
continue;
}
AddValueToDropdown(dropdown, '', '', 0);
// collect all of our dropdowns
dropdownElements.push(dropdown);
}
// add a custom validate function to the page
var funcValidate = function() {
var isValid = true;
var message = "";
for (var d = 0; d < dropdownElements.length; d++) {
if (0 === dropdownElements[d].selectedIndex) {
// require a selection other than the first item (our blank value)
if (isValid) {
isValid = false;
} else {
message += "\n"; // already had one error so we need another line
}
message += "Please choose a value for " + dropdownNames[d] + ".";
}
}
if (!isValid) {
alert(message);
}
return isValid;
};
var okButtons = GetOKButtons();
for (var b = 0; b < okButtons.length; b++) {
WrapClickEvent(okButtons[b], funcValidate);
}
}
_spBodyOnLoadFunctionNames.push("MyCustomExecuteFunction");
</script>
How about prepending a null option to the select menu of sharepoint.Like,
$('#idOfSelectMenu').prepend('<option value="" selected>(None)</option>');
I used this approach and append this code only in the NewForm.aspx because in EditForm.aspx it will override the selected option.

Resources