Friday, June 18, 2010

how to match lookup value using CAML

When you query a Lookup field using CAML by default it will be executed for matching the text of lookup that is not desired in many cases like my.

<Query>
<Where>
<Eq>
<FieldRef Name="LookupFieldName" />
<Value Type="Lookup">1</Value>
</Eq>
</Where>
</Query>

We need to just set a property "LookupId" to true in FieldRef Tag like the following


<Query>
<Where>
<Eq>
<FieldRef Name="LookupFieldName" LookupId="True" />
<Value Type="Lookup">1</Value>
</Eq>
</Where>
</Query>

This will instruct the CAML engine to use the value property of lookup to execute the match.

Thursday, June 17, 2010

Setting 20+ Lookup value at client side, JQuery

I have faced the issue many time when setting the value into sharepoint controls at client side. Here i will explain how to set the value in 20+ lookup control at client side using JQuery. First I tried to setting a value into its textbox and then firing a change event of textbox but that doesn't work. If you use JQuery to raise change event like this

$("[Title='TitleOfControl']").val("NewValue").change();

This event carry the srcElement property null that results in crash of "HandleChange" function in the start.

And if you try to raise the event like this

$("[Title='TitleOfControl']")[0]fireEvent('onchange');

There are many prerequisites to this approach like you have to first raise the click of lookup that will render the options in the DOM internally and then you have to select the appropriate option like this

var LookupInput = $("[Title='TitleOfControl']");
LookupInput.next().click();
$("select[id='" + LookupInput.attr("opt") + "']").find("option[value='"+ SelectedValue +"']").attr("selected","true");

and then raise the change event. This approach will only work if there are no duplicate text in the lookup otherwise it will fail.

Finally then i come to the following straight forward and working solution

var LookupInput = $("[Title='TitleOfControl']");
LookupInput.attr("match","SelectedText");
LookupInput.val("SelectedText");
$("input[id='" + LookupInput.attr("opthid") + "']").val("SelectedValue");

In this solution you need to set the value in TextBox, "opt" attribute of TextBox and in Hidden field "opthid" that is mentioned in attribute of TextBox. This solution worked for me like charm. Hope it will help others too.

HandleChange function that is called when lookup's textbox value changes
function HandleChange()
{
var ctrl=event.srcElement;
var str=ctrl.value;
var opt=document.getElementById(ctrl.opt);
ctrl.match=FilterChoice(opt, ctrl, str, "");
}

Writing Better SharePoint Code

http://www.sharepointproconnections.com/article/sharepoint/Writing-Better-SharePoint-Code.aspx