bkg2

Search

Sharing is Caring

Subscribe via RSS

Web Design Tag Cloud

$allowed_extensions $member $title 2011 ai allowedextensions amazon analytics apple attachedfiles attachedimages bad widget class name given blog blog date brands business news classes click here digital cms columns commission conflict content control creating a facebook following css data dataobject::get date format default search results design digital driving traffic east london embed embed twitter estate agent websites facebook facebook advertising facebook marketing fan pages fast hosts favicon favicon generator file is not a valid upload follow button football form future geo targeting customers google google adwords google local business centre google logo google maps google places has_many hmv if conditions if pos image inbound linking include blog entry integrate twitter internet turns 20 ip ip address javascript jquery link building livingsocial local businesses local businesses on google local business web design london london web design london web designers london web developers making money on the web menus migration mobile mobile site mobile version modeladmin mod_fcgid: http request length multiple class mutliple images new website nofollow oauth onlien marketing online ads online discounts online marketing online media online offers outbound links pac-man pageclass php warning: fopen promotions property web design property web devlopers property website random child rar real estate web design recommend recommended agency recommended agency register referral rel="nofollow" responsive rooms & studios search seo shoreditch show full fields shreditch web designers sidebar signups silverstripe silvestripe small business social media social social media social networks split strategy styles technology timeline twitter twitter api twitter api 1.1 twitter feed undefined uploadify http error url icon urlsegment userdefinedforms userforms user forms ux validationexception video vouchering vouchers web web builds web design web design development web designers web design shoreditch web design web development web developers web developers in shoreditch web developers london web developers shoreditch web development widgets wysiwyg youtube

How to include a SilverStripe form on any/every page

Here's a quick tutorial on the best way to include a SilverStripe function (e.g - a signup form) on any page, or every page, or a sidebar, or footer of your SilverStripe site.

<?php
class RegistrationForm extends Page {
}

class RegistrationForm_Controller extends Page_Controller {

// Make sure you set this to the right group.
// See http://doc.silverstripe.com/doku.php?do=show&id=recipes%3Aforms
private $defaultGroupID = 3;

/**
* This function lets you put a form on your page, using $Form.
*/
function SignupForm() {
return new Form($this, "SignupForm", new FieldSet(

    // List your fields here
    //new TextField("FirstName", "First name"),
    //new TextField("Surname"),
    new EmailField("Email", "")

), new FieldSet(

    // List the action buttons here
    new FormAction("SignupAction", "GO")

), new RequiredFields(

    // List the required fields here: "Email", "FirstName"

));
}


/**
* This function is called when the user submits the form.
*/
function SignupAction($data, $form) {

$email = Convert::raw2sql($data['Email']); // prevent sql injection
$existingUser = DataObject::get_one("Member", "Email = '$email'");
if($existingUser) {
 // Add a error message
 $form->addErrorMessage("Message","Sorry, that email address already exists. Please choose another.","bad");

 // Load errors into session and post back
 Session::set("FormInfo.RegistrationForm_RegistrationForm.data", $data);

 // Redirect back to form
 Director::redirectBack();
 return;
}


// Create a new Member object and load the form data into it
$member = new Member();
$form->saveInto($member);


// Write it to the database.  This needs to happen before we add it to a group
$member->write();

// Add the member to group. (Check if it exists first)
if($group = DataObject::get_one('Group', "ID = $this->defaultGroupID")) {


    $member->Groups()->add($group);
    // Redirect to a page thanking people for registering
    //Director::redirect('thanks-for-registering/');
    
    // In this example we are going to redirect back to the form, and simply add a thank you message.
$form->addErrorMessage("Message","Thank you.","good");
  // Redirect back to form
 Director::redirectBack();
 return;

}else{

    // Redirect to a failure page
    Director::redirect('registration-failed/');

}

}
}

Next, add this into your page.php file (this enables you to use the above function on any page)

function ShowForm(){
$get = DataObject::get_one('RegistrationForm');
return new RegistrationForm_Controller($get); }

Then to call your function in your template (e.g page.ss, footer.ss or sidebar.ss) just paste in this:

<% control ShowForm %>
$SignupForm
<% end_control %>

Includng a userform / userdefinedform on any page

If you're making use of userforms, then it's even easier! just add this to your page.php file:

function ShowForm(){
    $get = DataObject::get_one('UserDefinedForm');
    return new UserDefinedForm_Controller($get);
}

then in your template file:

<% control ShowForm %>
$Form
<% end_control %>

You can also create a form function within your Page.php for using throughout the site, very handy for newsletter signup forms in footers etc. Just create your form function in Page.php and ensure you list it as an "$allowed_actions". E.G:

public static $allowed_actions = array (
            'SignupForm'                                
    );

This method will come in handy throughout your time with SilverStripe so keep hold of it!

Troubleshooting

If you use any form of jquery throughout your site, you may find including the form will break things! The problem is that when you $get the userform and include it's controller you pull through the related JS files which may conflict with other scripts on your page. One way to avoid this is switch off js validation and ajax commenting by placing the following in your config file:

Validator::set_javascript_validation_handler('none'); 
PageCommentInterface::set_use_ajax_commenting(false);

As ever, if you see any problems with the above or can improve it, comments welcome below!

Posted by Ryan Badger on 10 June 2011 | 9 Comments

Tags: , , , ,

Post your comment

Comments

  • Hi Ryan,
    I'm having a problem getting this to work :(
    I'm using the userforms module and I've added the function in Page.php

    function ShowForm(){
    $get = DataObject::get_one('UserDefinedForm');
    return new UserDefinedForm_Controller($get);
    }

    But when I add the control to Page.ss:

    <% control ShowForm %>
    $Form
    <% end_control %>

    I get the white screen of death. If I remove $form and have 'Hello World' it works fine so for some reason $form is causing the problem.

    Any ideas?
    Cheers :)

    Posted by Brian, 03/09/2012 3:28pm (2 years ago)

  • The redirect is handled by this:

    // Redirect back to form
    Director::redirectBack();
    return;

    to send them somewhere else on submit, do something like this:

    Director::absoluteBaseURL() . "home";
    return;

    Posted by Ryan Badger, 17/08/2012 2:44pm (2 years ago)

  • Great post, thank you. Quick question (hopefully with a quick answer): how can I do a redirect upon submission? Clicking the Submit button works, but just presents the user with a reloaded page rather than a "Success" message.

    Posted by Prag, 15/08/2012 3:01pm (2 years ago)

  • if you can post a link to your files, I'll take a look if you like.

    Posted by Ryan Badger, 12/07/2012 9:56am (2 years ago)

  • Hi Ryan,

    Thanks for the pointers; I'm losing sleep with this one.
    The database fields and tables remain the same. I think the problem is calling the function.

    I've created a test function to output "Hello World" but this is not behaving as expected.

    I'm parking this for now (replacing it with a link to the form) but I will get to the bottom of it. When I do, I'll post the answer.

    Thanks!

    Patrick

    Posted by Patrick, 11/07/2012 10:36pm (2 years ago)

  • Is there any error message or anything?
    I would suggets you check the get method is actually finding a form... as this is quite old, check all the names are correct in the DB still. E.G - check there is actually a "UserDefinedForm"

    Also, make sure you don't have more than one UserDefinedForm

    Posted by Ryan, 02/07/2012 9:42am (2 years ago)

  • I know this is an old post but it is exactly what I am looking for.
    I am trying to get it to work with userform but can't get it right.

    I have placed the php in the page.php file (in the Page_Controller section (in /code/)

    I have placed this in the Page.ss file
    <% control ShowForm %>
    $Form
    <% end_control %>

    It doesn't call the Php to retrieve the page...New to SS and trying to get a form on each page for a fried. any help is much appreciated!

    Posted by Patrick, 02/07/2012 6:40am (2 years ago)

  • You just list the required fields in the relevant section:

    new RequiredFields(
    // List the required fields here: "Email", "FirstName"
    ));
    }

    To extend it further, just add more fields like this:

    function SignupForm() {
    return new Form($this, "SignupForm", new FieldSet(

    // List your fields here
    new TextField("FirstName", "First name"),
    new TextField("Surname"),
    new EmailField("Email", ""),
    new DateField("Date", ""),
    new TextField("Enquiry", "Comments/Questions"),
    )

    Posted by Ryan, 08/07/2011 2:46pm (3 years ago)

  • Nice tutorial, but how to do that it displays an error message when someone leaves a blank field?

    And my second question. How to extend this form of name and content?

    Sorry for my english

    Posted by Lobek, 07/07/2011 12:22am (3 years ago)

RSS feed for comments on this page | RSS feed for all comments