Sharepoint web part form validation blocks updating web part settings - sharepoint

I have written a web part in C# for Sharepoint 2007 which has a single field which is validated as a required field using RequiredFieldValidator(). The web part also has some configuration fields (ones you edit by clicking on Modify Shared Web Part).
When I make changes to these fields and try to apply them, the validation of the user field kicks in and prevents the update, even though I am not submitting the form. I am only trying to submit the settings. The web part may be used in a few places on our farm, so site collection administrators need to be able to change the settings - at the moment it is not friendly enough for these users to do so.
Here is where I validate the user field:
// Validate form field - required field, and max length is 100 characters.
InputFormRequiredFieldValidator messageRequiredValidator = new InputFormRequiredFieldValidator();
messageRequiredValidator.ControlToValidate = txtMessage.ID;
messageRequiredValidator.ErrorMessage = "You must write a message to send!";
messageRequiredValidator.Display = ValidatorDisplay.Dynamic;
messageRequiredValidator.Text = "<img src=\"/_layouts/images/CNSCA16.gif\"/> You must write a message to send.";
tc.Controls.Add(messageRequiredValidator);
Here is where I define one of the configuration fields:
private string recipientEmailAddress = "sender#domain.tld";
[WebBrowsable(true),
Personalizable(true),
WebPartStorage(Storage.Shared),
WebDescription("Email address the form should be sent to"),
WebDisplayName("Recipient Email Address"),
SPWebCategoryName("Email Settings")]
public string RecipientEmailAddress
{
get { return recipientEmailAddress; }
set { recipientEmailAddress = value; }
}
This is the first web part I have written, so there may be some subtleties I am missing in how to do admin configuration and validation of user submitted fields.

Ok - I've found the key to this. You can add a validationGroup property to each validator, and to the button that causes the validation. So I changed my code to include:
messageRequiredValidator.validationGroup = "UserInput";
and a similar property to my submit button. Now when I click on Ok in the ToolPane, it doesn't validate the UserInput validation group. That only happens when I click on my Submit button.

You can dynamically disable validations on OK, Cancel buttons in ApplyChanges method:
ToolPane pane = Zone as ToolPane;
if (pane != null)
pane.Cancel.CausesValidation = false;
OR you can also check if editor pane is open and disable validation in webpart :
WebPartManager wpm = WebPartManager.GetCurrentWebPartManager(Page);
if (wpm.DisplayMode == WebPartManager.EditDisplayMode)
{
//Page is in edit mode
}

I would suggest to use the SharePoint validation control.

Related

Load data in custom form by using Kentico 9

I searched the whole web and I couldn't found any good topic which expose the proper way to do it.
I have a very simple web which I developed using Kentico 9 CMS. This web only contains two subpages and a header to navigate between those.
The "Home" subpage contains a custom form which remains connected to a SQL table which is populated every time you press submit with certain data.
On the other hand, the other page, shows the stored data by using a custom web part which connects to the DB by using BizFormItemProvider and this object is used as a layer to binding the data in a control.
Now is my point. If you see, there is a button to "Edit" a certain row and my intention is to Redirect to "Home" (which contains the form) and sending via QueryString the ID of the row attempted to edit.
I was unable to understand how can you re-fill the form with its data using an ID.
Maybe because I never worked with a CMS before, I'm looking the development such as pure ASP.NET and it could not be the correct one.
Custom
Given that your solution uses a custom form for entering the data, as well as a custom web part for listing the stored data, you will need to use a custom solution to handle the editing of data, as well.
In the custom webpart on the Home page, in a load event, you can retrieve the form data and set the values on the form controls.
protected void Page_Load(object sender, EventArgs e)
{
// Ensure that the form is not being posted back,
// to prevent entered data from being overwritten
if(!IsPostBack)
{
// Get the form item ID from the query string
var personId = QueryHelper.GetInteger("personId", 0);
if(personId > 0)
{
// Get the biz form item, and set form control values
var bizFormItem = BizFormItemProvider.GetItem(personId, "customFormClassName");
txtFirstName.Text = bizFormItem.GetStringValue("FirstName", string.Empty);
}
}
}
Similarly, when Submit is clicked, you can update the existing form item with the new data
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
// Get the form item ID from the query string
var personId = QueryHelper.GetInteger("personId", 0);
if(personId > 0)
{
// Retrieve the existing biz form item,
// and update it from the form control values
var bizFormItem = BizFormItemProvider.GetItem(personId, "customFormClassName");
bizFormItem.SetValue("FirstName", txtFirstName.Text);
bizFormItem.Update();
}
else
{
// Your code for inserting a new form item...
}
}
The Kentico way
You should really consider using the Kentico form engine for accomplishing this task. Instead of using a custom form for entering the data, use the built-in On-line form webpart.
The benefits are numerous, such as:
Ability to set the form layout through the CMS, and use alternative layouts
Automatic confirmation email to the submitter of the form, as well as notification emails to the administrators
To accomplish your task, you can customise the On-line form webpart to support loading of existing data.
In the bizform.ascx.cs file, add code to the SetupControl method:
protected void SetupControl()
{
if (StopProcessing)
{
// Existing code...
}
else
{
// Existing code...
// Get the form item ID from the query string
var personId = QueryHelper.GetInteger("personId", 0);
if(personId > 0)
{
// Get the biz form item, and set form control values
var bizFormItem = BizFormItemProvider.GetItem(personId, "customFormClassName");
if(bizFormItem != null)
{
// Set the item ID
viewBiz.ItemID = bizFormItem.ItemID;
}
}
}
}
This will automagically switch the form to Edit mode, instead of Insert mode, as soon as you set the ItemID property. Clicking the Submit button will save changes on the existing form item.
You will not need to worry about validation in your code, and inserting data will still work.
Is this a contact form that you are using Kenticos built in form application for, or is it a custom form? If it is a custom form you can create a transformation with a link that will contain the ID. If it is a biz form, you can still create a transformation in Page Types (create a new page type and select "The page type is only a container without custom fields"), then write a custom query to get the biz form data, and use a repeater to display the data with that transformation.

Always open the default form in CRM on the case entity

We have two forms for the case entity. The default case form is heavily customized and has become rather slow to work with. The second form, called 'fastcase', is a lightweight version of the default case form. Both forms are being used by the same users. The fastcase form is opened from a link in SharePoint. We want that the default case form is always opened when working from within CRM.
I was wondering if, and how, it is possible to force CRM to always open the default case form when working from within CRM.
The only thing I could find was this link, but I have a feeling that the solution with navigate will also force the SharePoint fastcase form to open in the default case form. Working with different user roles and groups is also not an option as suggested there.
First of all: You are not using forms they are supposed to be used. Forms are role based and you are trying to use them for something else. Anyway, I totally understand your idea and I have been in the same situation :)
You need to do a little magic trick in CRM to make a form sticky. CRM stores the Most Recently Used (MRU) forms in a special entity called UserEntityUISettings. This entity stores UI settings per entity per user in xml.
What you need to do is to prevent CRM from changing this entity whenever the user changes the form for a given entity. Basically you want to control the attribute called lastviewedformxml. You can get some inspiration from this blog post: https://community.dynamics.com/crm/b/gonzaloruiz/archive/2014/11/19/avoiding-form-reload-when-switching-crm-forms-based-on-a-field.aspx
Happy coding...
You can open CRM forms in this way:
function OpenForm()
{
var parameters = {};
var id = GetFormId("account", "FormName");
parameters["formid"] = id;
Xrm.Utility.openEntityForm("account", null, parameters);
}
function GetFormId(formEntity, formName) {
var serverUrl = Xrm.Page.context.getServerUrl();
var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += "SystemFormSet?$top=1&$filter=ObjectTypeCode eq '" + formEntity + "' and Name eq '" + formName + "'";
var service = new window.XMLHttpRequest;
var id;
if (service != null) {
service.open("GET", oDataEndpointUrl, false);
service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json, text/javascript, */*");
service.send(null);
var requestResults = eval('(' + service.responseText + ')').d;
if (requestResults != null && requestResults.results.length == 1) {
var rec = requestResults.results[0];
id = rec.FormId;
}
}
return id;
}
Depends the way you are calling the form from sharepoint you call the form you need and from CRM you let it handles in the native way.

Write the plugin when Selecting the lookup flied and according to filed selection Show/Hide Address filed in form.....?

We Have Contact Entities in contact Entitie one lookup filed company Name in that lookup having two values 1.Account and 2.Contact . When we are selecting contact show the address filed when we select account hide the address filed we needs to write the plugin to Execute that works. Kindly any one help me on the same.
Thanks!!
Rajesh Singh
First, if you need to make change on a form, you can't use plug-ins. Plug-ins are made for bussinees logics, like Update another record when the first one is created, make complex logic, etc...
What you need it is a javascript that executes on the OnLoad of the form and OnChange event in that OptionSet.
The lines you are looking for are:
function ShowField()
{
// The field is present on the form so we can access to its methods
var optionSet = Xrm.Page.getAttribute("custom_attribute");
if (optionSet == undefined)
{
return;
}
// The control is present on the form so we can access to its methods
var controlAddress = Xrm.Page.getControl("custom_address");
if (controlAddress == undefined)
{
return;
}
var valueOptionSet = optionSet.getValue(); // This is the value you set creating the OptionSet
switch (valueOptionSet)
{
case 0: // Your account value, show
controlAddress.setVisible(true);
case 1: // Your contact value, hide
controlAddress.setVisible(false);
default:
return;
}
}
You need to register a web resource and register the event, if you need more information about the code or why this stuff is here and why this not just tell me.

Validate a Single line of text column type of list in sharepoint 2010 to accept only alphabets?

How to validate a Single line of text column type of list in sharepoint 2010 to enter accept only alphabets? no special character and no number should be allowed in that field.
Probably one of the best ways to apply client-side validation in SharePoint 2010 would be to override PreSaveAction handler.
PreSaveAction function is a user defined function that allows to
override standard behavior for a Save button handler in List Forms on the client-side.
Regarding validation expression, we could use /^[a-zA-Z]+$/ regular expression to accept only letters
Let's say we need to validate Notes field in Links list to accept only letters, then the following steps demonstrate how to apply those changes:
Steps:
Open New Form page in Edit mode
Add Content Editor web part on the page
Insert the code provided below into Content property of Content Editor web
part
Code:
<script>
function isLetter(val) {
var re = /^[a-zA-Z]+$/;
return re.test(val);
}
function PreSaveAction(){
var commentsBox = findFieldControl('Notes'); //find field control by title
if (!isLetter(commentsBox.val())) {
var errorHtml = '<br/><span class="ms-formvalidation"><span role="alert">Only letters are allowed<br></span></span>';
commentsBox.after(errorHtml);
return false;
}
return true;
}
function findFieldControl(fieldTitle)
{
var control = $('[title="' + fieldTitle + '"]');
return control;
}
</script>​​​​​​
Results
Some additional information about client-side validation in SharePoint 2010/2013 could be found in this post.

Cannot save all of the property settings for this Web Part - Sharepoint

"Cannot save all of the property settings for this Web Part. The
default namespace "http://schemas.microsoft.com/WebPart/v2" is a
reserved namespace for base Web Part properties. Custom Web Part
properties require a unique namespace (specified through an
XmlElementAttribute on the property, or an XmlRootAttribute on the
class)."
No where do I get help regarding this error.
This is when adding custom properties to my webpart, why cant I save the properties when I edit my webpart and click on save/apply? (then I get that error)
Code--
[DefaultProperty("Text"), ToolboxData("<{0}:CustomPropertyWebPart runat=server></{0}:CustomPropertyWebPart>"),
XmlRoot(Namespace = "ExecuteStoreProc")]
public class CustomPropertyWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
const string c_MyStringDefault = "Sample String";
}
// Create a custom category in the property sheet.
[Category("Custom Properties")]
// Assign the default value.
[DefaultValue(c_MyStringDefault)]
// Property is available in both Personalization
// and Customization mode.
[WebPartStorage(Storage.Personal)]
// The caption that appears in the property sheet.
[FriendlyNameAttribute("Custom String")]
// The tool tip that appears when pausing the mouse pointer over
// the friendly name in the property pane.
[Description("Type a string value.")]
// Display the property in the property pane.
[Browsable(true)]
[XmlElement(ElementName = "MyString")]
// The accessor for this property.
public string MyString
{
get
{
return _myString;
}
set
{
_myString = value;
}
}
Can you try going to Site Settings > Galleries > Web Part > New
In that window, put a checkbox next to the webpart you are trying to add, then click Populate
If its populate correctly then it is working otherwise there is some error in the webpart.
Return to your webpage where you want to add the webpart, try to add the webpart by selecting it in the gallery.
If this works (you were able to add it to your page), you can open the webpart added in your webpart gallery (Site Settings > Galleries > Web Part) and compare it to your own .dwp file to see what you did wrong.
Hope this helps

Resources