Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Rik Helsen 670 posts 873 karma points
    Nov 23, 2010 @ 10:37
    Rik Helsen
    0

    Using data from current logged in member to prefill fields in form?

    Hi,

    I'd looking for a way to include member properties as pre-entered text in a contour form (stuff such as name etc)

    anonymous users would complete the entire form, members would only  need to enter the information we don't have yet.

    can this be done?

  • Ismail Mayat 4511 posts 10092 karma points MVP 2x admin c-trib
    Nov 23, 2010 @ 10:57
    Ismail Mayat
    0

    Rik,

    One possible way in theory would be to update your login control so that when they login you put into session some of these fields like name with key that corresponds to contour field name then on the contour form for default values you could pick up those values from session, [%name] something like that in default field will pick up value from session? I would check the documentation, I have dont it with setting default values with querystring parameters.

    Another way potentially relates to something I recently recently with contour form where i needed to have some additional validation on a registration form built by contour I needed the following:

    1. Password to be entered twice to ensure correctly entered
    2. Email entered twice to ensure correctly entered
    3. Email need to be checked that it was not already in use
    4. Password as greater than 7 chars with 2 numeric
    I could have put it together with some custom datatypes for contour but i did it another way which you could use to solve your issue. I created a macro with was server control that looked like
    /// <summary>
        /// servercontrol macro to inject in richer field validation for contour
        /// forms, contour only handles mandatory or regex
        /// </summary>
        public class ValidateRegistration:WebControl
        {
            public bool PerformUniqueEmailTest { get; set; }
            #region private properties
            
            private List<TextBox> textBoxes;
            private List<Label> labels;
            private const string emailTextBoxLabel = "Email address";
            private const string emailTextBoxConfirmLabel = "Re type email address";
            private const string passwordTextBoxLabel = "Password";
            private const string passwordTextBoxReTypeLabel = "Re type password";
            private const string matchEmailError = "Email addresses do not match";
            private const string matchPasswordsError = "Passwords do not match";
            private const string contourErrorCssClass = "contourError text";
            private const string contourLabelErrorCssClass = "contourError fieldLabel";
            private string validationGroup = string.Empty;
            
            #endregion
            #region protected methods
            protected override void OnInit(EventArgs e)
            {
                base.OnInit(e);
                if (PerformUniqueEmailTest)
                {
                    AddUniqueEmailValidatorToEmail();
                    AddCompareValidators();
                    //password strength checker is reg ex in contour form
                }
            }
            protected override void OnPreRender(EventArgs e)
            {
                base.OnPreRender(e);
                base.OnLoad(e);
                if (Page.IsPostBack)
                {
                    SetContourErrorCssToCustomValidators();
                }
            } 
            #endregion
            #region private methods
            private void SetContourErrorCssToCustomValidators()
            {
                var validators = ExtensionMethods.ControlsByTypeUsingAncestor<CustomValidator>(this.Page);
                foreach (CustomValidator validator in validators)
                {
                    if (!validator.IsValid)
                    {
                        string textBoxId = validator.ControlToValidate;
                        var tbEmail = (from t in textBoxes
                                       where t.ID == textBoxId
                                       select t).FirstOrDefault();
                        tbEmail.CssClass = contourErrorCssClass;
                        var associatedLabel = (from l in labels
                                               where l.AssociatedControlID == tbEmail.ID
                                               select l).FirstOrDefault();
                        associatedLabel.CssClass = contourLabelErrorCssClass;
                    }
                }
            }
            private void AddCompareValidators()
            {
                TextBox emailBox = GetTextBoxFromAssociatedLabel(emailTextBoxLabel);
                CustomValidator compareEmails = GetCustomCompareValidator("matchEmails",
                                                                    emailBox.ID,
                                                                    matchEmailError, false);
                emailBox.Parent.Controls.Add(compareEmails);
                TextBox passwordBox = GetTextBoxFromAssociatedLabel(passwordTextBoxLabel);
                CustomValidator comparePasswords = GetCustomCompareValidator("matchPasswords",
                                                                   passwordBox.ID,
                                                                   matchPasswordsError, true);
                passwordBox.Parent.Controls.Add(comparePasswords);
            }
            private void AddUniqueEmailValidatorToEmail()
            {
                TextBox emailBox = GetTextBoxFromAssociatedLabel(emailTextBoxLabel);
                if (emailBox.ID != string.Empty)
                {
                    validationGroup = GetContourValidationGroup();
                    var uniqueEmail = new CustomValidator
                                                     {
                                                         ID = "uniqueEmail",
                                                         ErrorMessage = "Email address already in use",
                                                         ControlToValidate = emailBox.ID,
                                                         EnableClientScript = false,
                                                         Display = ValidatorDisplay.None,
                                                         CssClass = "contourError",
                                                         ValidationGroup = validationGroup
                                                     };
                    uniqueEmail.ServerValidate += uniqueEmail_ServerValidate;
                    emailBox.Parent.Controls.Add(uniqueEmail);
                }
            }
            private TextBox GetTextBoxFromAssociatedLabel(string textBoxLabel)
            {
                labels = ExtensionMethods.ControlsByTypeUsingAncestor<Label>(this.Page);
                TextBox tbEmail = new TextBox();
                if (labels.Count() != 0)
                {
                    Label labelForEmail = (from t in labels
                                           where t.Text.Contains(textBoxLabel)
                                           select t).FirstOrDefault();
                    if (labelForEmail != null)
                    {
                        string emailTbId = labelForEmail.AssociatedControlID;
                        textBoxes = ExtensionMethods.ControlsByTypeUsingAncestor<TextBox>(this.Page);
                        if (textBoxes.Count() != 0)
                        {
                            tbEmail = (from t in textBoxes
                                       where t.ID == emailTbId
                                       select t).FirstOrDefault();
                        }
                    }
                }
                return tbEmail;
            }
            private string GetContourValidationGroup()
            {
                string vGroup = string.Empty;
                List<RequiredFieldValidator> reqValidators = ExtensionMethods.ControlsByTypeUsingAncestor<RequiredFieldValidator>(this.Page);
                var validatorWithGroupSet = (from v in reqValidators
                                             where v.ValidationGroup != string.Empty
                                             select v).FirstOrDefault();
                vGroup = validatorWithGroupSet.ValidationGroup;
                return vGroup;
            }
            private CustomValidator GetCustomCompareValidator(string validatorId, string control1ToValidate, string errorMessage, bool passwordValidate)
            {
                var cv = new CustomValidator()
                {
                    ID = validatorId,
                    EnableClientScript = false,
                    ValidationGroup = validationGroup,
                    ControlToValidate = control1ToValidate,
                    ErrorMessage = errorMessage,
                    Display = ValidatorDisplay.None
                };
                if (passwordValidate)
                {
                    cv.ServerValidate += cv_ServerPasswordValidate;
                }
                else
                {
                    cv.ServerValidate += cv_ServerEmailValidate;
                }
                return cv;
            } 
            #endregion
            #region custom validators
            void uniqueEmail_ServerValidate(object source, ServerValidateEventArgs args)
            {
                var cv = (CustomValidator)source;
                args.IsValid = true;
                if (cv.ControlToValidate != string.Empty)
                {
                    TextBox tb = (from t in textBoxes
                                  where t.ID == cv.ControlToValidate
                                  select t).FirstOrDefault();
                    Member m = Member.GetMemberFromEmail(tb.Text);
                    if (m != null)
                    {
                        args.IsValid = false;
                    }
                }
            }
            void cv_ServerPasswordValidate(object source, ServerValidateEventArgs args)
            {
                string password = args.Value;
                string confirmPassword = GetTextBoxFromAssociatedLabel(passwordTextBoxReTypeLabel).Text;
                if (password == confirmPassword)
                {
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                }
            }
            void cv_ServerEmailValidate(object source, ServerValidateEventArgs args)
            {
                string emailAddress = args.Value;
                string confirmEmail = GetTextBoxFromAssociatedLabel(emailTextBoxConfirmLabel).Text;
                if (emailAddress == confirmEmail)
                {
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                }
            }
           
            #endregion
        }

     

    This does the following OnInit I get the label for email control and from that get the associated textbox email and assign a new validator to it, i do similar for attaching other validators, so you could in a similar server control check if member is logged in get their profile and fields then find the fields on the form and set the values.

    The lookup code looks like

    /// <summary>
            /// get find control method using generics
            /// </summary>
            /// <typeparam name="T">type of item you want</typeparam>
            /// <param name="ancestor">parent to start looking from</param>
            /// <returns>collection of T items</returns>
            public static List<T> ControlsByTypeUsingAncestor<T>(Control ancestor) where T : Control
            {
                var controls = new List<T>();
    
                //Append to search results if we match the type 
                if (typeof (T).IsAssignableFrom(ancestor.GetType()))
                {
                    controls.Add((T) ancestor);
                }
    
                //Recurse into child controls 
                foreach (Control ctrl in ancestor.Controls)
                {
                    controls.AddRange(ControlsByTypeUsingAncestor<T>(ctrl));
                }
    
                return controls;
            }

    its basically a recursive findcontrol method so in theory you could do something similar.

    Regards

     

    Ismail

  • Comment author was deleted

    Nov 24, 2010 @ 08:35

    We'll add support for that in the next release so you could do something like setting the default value to {member.propertyName}

    But for now the session workaround should be the easiest

  • Bas Schouten 135 posts 233 karma points
    May 19, 2011 @ 12:18
    Bas Schouten
    0

    Hi everyone,

    Does anyone know if I can use Tim's solution already?

    Cheers,

    Bas

Please Sign in or register to post replies

Write your reply to:

Draft