Another way of sending Data from External List to Data View Web Part of Form page of a List

Previously, I told about how you can send Filtered data from an external list to a New/Edit form page’s Data View Web Part by connecting the web parts. Today, I will show another easy way to populate Data within a Data View Web Part sent from a External List.

This time around, I have used Inline Coding inside the Form Page (You have to go in Advanced mode to write inline code and modify the web.config for allowing).

Open up your form page and find the following:

<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

I have to use my code inside this tag. So, first of all create some Text Fields which will grab the values of the Data sent from the External list.

<asp:TextBox ID="txtID" runat="server" Text="" Visible="false"/>
<asp:TextBox ID="txtFullName" runat="server" Text="" Visible="false"/>
<asp:TextBox ID="txtEmail" runat="server" Text="" Visible="false"/>
<asp:TextBox ID="txtPhone" runat="server" Text="" Visible="false"/>

Note that, I set the visibility to false as obviously you don’t want to show these on your Forms

For writing C# code inside the form, we have to add a tag like the following:

<script runat="server" type="text/c#">

Now, I need to write the logic inside the Page_Load event as that is when my External List will interact with this form and populate the fields.

protected void Page_Load(object sender, EventArgs e)
        {
         
       //Get the current site
         SPWeb currentWeb = SPContext.Current.Web;
       //Get the current user
         SPUser currentUser = currentWeb.CurrentUser;
        //Get the current user's login name
              string username1 = currentWeb.CurrentUser.LoginName.ToString();
              
      //As current username's format is ABC\username, i need to use substring to get "username"
             string username2 = username1.Remove(0,4); 

      //This username exist in the external List as Upper Case
             string currentUsername=username2.ToUpper(); 
         
      //Elevate the permission of current user to use System Account
         SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                
                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                        
                        //Get the List of this current form page, in my case it is "Request For Change"
                         SPList list1 = web.Lists["Request For Change"];  
                            
                            bool isMember=false;
                          //Checking the current user whether he belongs to a particular group
                            isMember=SPContext.Current.Web.IsCurrentUserMemberOfGroup(web.Groups["Request For Change Members"].ID);
                            bool isModerator=false;
                            isModerator=SPContext.Current.Web.IsCurrentUserMemberOfGroup(web.Groups["Request For Change Moderators"].ID);
                            bool isAdmin=false;
                            isAdmin=SPContext.Current.Web.IsCurrentUserMemberOfGroup(web.Groups["Request For Change Admin"].ID);

                       //If the user does not belong to any group, redirect him to the main home page of the site
                            if(isMember==false && isModerator==false && isAdmin==false)
                            {
                                Context.Response.Redirect(SPContext.Current.Web.Url.ToString());
                            }

                  //Get the External List, in my case the name is "eBusinessInfo"      
              SPList list=web.Lists["eBusinessInfo"];
                 //Using CAML
               SPQuery theQuery=new SPQuery();

                            theQuery.ViewFields="<FieldRef Name='ID' /><FieldRef Name='FULL_NAME' /><FieldRef Name='EMAIL' /><FieldRef Name='WORK_PHONE' /><FieldRef Name='USER_NAME' />" ;
                            theQuery.Query = @"<Where>
                            <Eq>
                                <FieldRef Name='USER_NAME' />
                                <Value Type='Text'>"+ currentUsername +@"</Value>
                            </Eq>
                            </Where>";
                            //get the Result of CAML query
                            SPListItemCollection foundItem = list.GetItems(theQuery);
                           //Store the ID, Full Name, Email and Phone inside the TextBox that we created before
                            txtID.Text= foundItem[0]["ID"].ToString();
                            txtFullName.Text = foundItem[0]["FULL_NAME"].ToString();
                            string strEmail= foundItem[0]["EMAIL"].ToString();
                            if(foundItem[0]["WORK_PHONE"]==null)
                            txtPhone.Text= "";
                            else
                            txtPhone.Text=foundItem[0]["WORK_PHONE"].ToString();
                            //string strPhone=foundItem[0]["WORK_PHONE"].ToString();
                            if(strEmail != null)
                            
                            txtEmail.Text = foundItem[0]["EMAIL"].ToString();
                            else
                            txtEmail.Text= "N/A";
                            
                        
                            }
                        }
                    
                    });

        }

</script>

Upto now, I have retrieved the value from the external list using a CAML query and stored the value inside the TextBox Fields. Now, In order to use these values inside my form, I have to find the following web part zone:

<WebPartPages:WebPartZone runat=“server” FrameType=“None” ID=“Main” Title=“loc:Main”><ZoneTemplate>

 
add the parameters inside this web part zone:
<ParameterBinding Name="paramID" Location="Control(txtID, Text)" DefaultValue=""/> 
<ParameterBinding Name="paramFullName" Location="Control(txtFullName, Text)" DefaultValue=""/>
<ParameterBinding Name="paramEmail" Location="Control(txtEmail, Text)" DefaultValue=""/>
<ParameterBinding Name="paramPhone" Location="Control(txtPhone, Text)" DefaultValue=""/>

 

Then, add the parameters inside the XSLT right after this web part zone.

<xsl:param name="paramID" />
<xsl:param name="paramFullName" />
<xsl:param name="paramEmail" />
<xsl:param name="paramPhone" />

Now, Instead of using SharePoint:FormField for the desired fields, change those like the following:

<asp:TextBox runat="server" id="ff1{$Pos}" ReadOnly="True" Text="{$paramID}" __designer:bind="{ddwrt:DataBind('i',concat('ff1',$Pos),'Text','TextChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@ID')}"/>

While changing this, do not forget to change “Value” and “ValueChanged” to “Text” and “TextChanged” respectively inside the Tag. That’s it. Now, save the form and see the result!

Advertisements

Hide form fields using JQuery and SharePoint Web Services

There are many occasions when we need to hide certain form fields based on some permission / group settings. Well, there is an easy way of achieving this using a JQuery plugin called “SPServices” which is free to use.

Using this plugin, you can call any in built SharePoint web service, get the value retrieved by the web services and use it in your form easily.

In this example, I have three types of users for a specific list which are “Users”, “Moderators” & “Admin”. I would like to check the current user which group he belongs and based on that I am going to hide/show some fields.

First of all, Download the SPServices plugin from here and then open your form in Advanced Mode using SharePoint Designer 2010 and look for the following line:

<asp:Content ContentPlaceHolderId="PlaceHolderBodyAreaClass" runat="server">

Add the script for SPServices:

<script type="text/javascript" src="http://(YOUR SITE URL)/(SAVED FOLDER FOR SPSERVICES)/jquery.SPServices-0.6.2.min.js"></script>

and add the following code under that

<script type="text/javascript">
    $(document).ready( function ()
    {
                    var isUserOnly = false; //User group member only
            var isModerator= false;
            var isAdmin=false;
                    var MODERATORGROUP = "Moderators"; // SPGroup named “Moderators”
                    var ADMINGROUP = "Admin";  // SPGroup named “Admin”

                    $().SPServices
                    ({
                      operation: "GetGroupCollectionFromUser", //Calling GetGroupCollectionFromUser.asmx web service
                      userLoginName: $().SPServices.SPGetCurrentUser(), //Calling Current User
                      async: false,
                      completefunc: function(xData, Status)
                      {
                                        $(xData.responseXML).find("Groups").each(function() //Retrieving the values from Group method of Web Service
                                        {
                                             $(this).find("Group").each(function()  //Parsing through all the groups the current user belongs to
                                             {
                        //Checking whether Current User belongs to Admin Group

                                                  if(($(this).attr("Name").toLowerCase() === ADMINGROUP.toLowerCase()))
                                                    isAdmin = true;
                        //Checking whether Current User belongs to Moderators Group

                          else if(($(this).attr("Name").toLowerCase() === MODERATORGROUP.toLowerCase()))
                            isModerator=true; 

                        //If Current User does not belong to Moderators or Admin, then definitely a normal user

                          else
                            isUserOnly=true;
                                             });
                                        });
                         }
                   }); // Closing SPServices Method

                   if(isUserOnly)
                   {

                        //Hide fields as this user is Not a member of Modeartora or Admin Group

               jP.Form.readForm("http://teamradiant/sites/rfc/").Comments.hide();
               jP.Form.readForm("http://teamradiant/sites/rfc/").Approval.hide();
                    }
           if(isModerator)
            {
            //Hide Approval field if the current user belongs to Moderators Group

                jP.Form.readForm("http://teamradiant/sites/rfc/").Approval.hide();

            //Show Comments field if the current user belongs to Mdoerators Group

                jP.Form.readForm("http://teamradiant/sites/rfc/").Comments.hide();
            }
            if(isAdmin)
            {

            //Show both fields if the current user belongs to Admin group

                 jP.Form.readForm("http://teamradiant/sites/rfc/").Comments.show();
                 jP.Form.readForm("http://teamradiant/sites/rfc/").Approval.show();
            }

   });
</script>
After that save the Form, and check that it works!

How to Send Filtered Data from an External List to a Data View Web part of a Form Page?

When we develop Custom Form Page, on various occasions we need to retrieve Form Field Data from a SharePoint List or another External List.  In this example,  I am going to show how you can obtain data from an External List and send those data to your form fields while loading a New Form page.

Keep in your mind that in SharePoint 2010, when we create a new Form from SP Designer 2010, we get a Data View Web Part for the Form Fields.

First, let us create a custom Form page (which is a Web Part page) from the SP Designer 2010. Then, create parameters for fields which we need to get the data from the external list. To insert parameters in SP Designer 2010, Select Parameters from the Ribbon->Options. You should see the following window:

image

Now, click on “New Parameter”. For my requirements, I have created four new parameters for “ID”, “Name”, “Email” and “Phone”. Give any name for the Parameter name and Choose none for Parameter Source and none for Default Value. Click Ok.  Save your page.

image

Then, open that page in your Web Page and go to Site Actions->Edit Page. Now, you will see the web part zones where you can add a new web part. Click on “Add a Web Part” and choose your desired External List from the pop up window. Click “Add”. After adding the external list web part, select from the top right corner where you will get similar to the following window:

image

Choose Connections->Send Row of Data To. Here, “Request For Change” is the web part where I want to send the values.

image

Choose, “Get Parameters From” from Connection Type. Then select the tab “Configure Connection”.

image

Click Finish. Now, with this setting, I can only pass one value as a parameter to my consumer web part. This is a shortcoming of using web front end to create web part connection. If we want to send another, we cannot do so as we get the following window where there is no option for inserting additional fields.

image

To get rid of this situation, let us switch back to SP Designer 2010 and open the Custom New Form page in Advanced Edit mode. Here, you will notice that the External List which we added is being shown as “XSLTListViewWebPart”. Select the web part and click on “Manage Connections”. You will get like the following window:

image

Notice that our earlier connection which we created from the Web Front end is already there. Click on “Modify”.

image

You can now see the details of this web part connection (Source, Target, Action). Select “Send Row of Data To”.

image

Now, select “Connect to a Web part on this page”. Click “Next”.

image

Here, you can see the Target Web part and Target Action. Choose Target action “Get Parameters From”.

image

Here is the thing; you can now map multiple fields with multiple parameters that you created before.  For my case:

Columns in eBusinessInfo (External List)            Inputs to Request For Change (Consumer Web Part)

Email                                                                    paramEmail

ID                                                                         paramID

Work_Phone                                                        paramPhone

Full Name                                                             paramName

After mapping all the fields, click Next-> Finish. Now, my web part connection between the external list and form Data View Web Part is complete. But, yet I cannot use the values directly as a parameter. To do so, I need to modify my required Fields (SharePoint:FormField) and convert those as “TextBox” to use the parameter.

For example: For “Name” field, I have got the following form field.

<SharePoint:FormField runat="server" id="ff3{$Pos}" ControlMode="New" FieldName="Full_x0020_Name" __designer:bind="{ddwrt:DataBind('i',concat('ff3',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Full_x0020_Name')}"/>

 

Convert the above form field as:

<asp:TextBox runat="server" id="ff3{$Pos}"  Text="{$paramName}" ReadOnly="True" __designer:bind="{ddwrt:DataBind('i',concat('ff3',$Pos),'Text','TextChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Full_x0020_Name')}"/>

 

Important thing to note: Remove “ControlMode” and “FieldName” property and Change “Value” to “Text” and “ValueChanged” to “TextChanged” inside _designer: bind property.  As I want the Name to be read only , that’s why I kept ReadOnly=”True”.

Convert the other three fields in the same way and then preview your Form Page. I forgot one thing to mention here; of course, you don’t want to show up your External list in your New Form page. To do so, go to the property of the External List Web part and set “Hidden=True”. Now, if you browse your page in preview mode, you will see the values got populated in your Data View Web Part of your new Form Page.

How to use Inline Code In SharePoint Designer 2010?

SharePoint 2010 does not allow inline coding for Form pages created from SP Designer. If you use inline coding in any form page (New, Edit or Display), you will get into an error which will say “Code Block is not allowed on this page”.

To resolve this, you need to change the web.config file of your web application.

For example: If your web application uses Port 80,  you have to go to to port 80 directory which generally resides in C:\inetpub\wwwroot\wss\VirtualDirectories\80

go inside that port number directory where you will find the web.config file where you will need to modify. Look for the tag <PageParserPaths> in the web.config.

Now, if you want to allow inline coding for all the site collections under that web application you will need to add the following:

<PageParserPaths>
        <PageParserPath VirtualPath="/*" CompilationMode="Always" AllowServerSideScript="true" IncludeSubFolders="true" />
</PageParserPaths>

Now, above code will allow inline coding in all the form pages in SharePoint Designer 2010 under that particular web application across all the site collections and sites. Use IncludeSubFolders=”true” if you want that coding enabled for all the site collections or sites under that web app.

If you want to allow inline coding only for a particular site collection you will need to change the code to the following:

<PageParserPaths>
        <PageParserPath VirtualPath="/sites/sitename/*" CompilationMode="Always" AllowServerSideScript="true" IncludeSubFolders="true" />
 </PageParserPaths>

 

For a particular page inside a site or site collection:

<PageParserPaths>
        <PageParserPath VirtualPath="/sites/sitename/PageName.aspx" CompilationMode="Always" AllowServerSideScript="true" IncludeSubFolders="true" />
</PageParserPaths>

Change the PageName.aspx to your page name.

For master page of your root level site collection:

<PageParserPaths>
    <PageParserPath VirtualPath="/_catalogs/masterpage/*" CompilationMode="Always" AllowServerSideScript="true" IncludeSubFolders="true" />
</PageParserPaths>