Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Adding attributes in a form


Reply


3 Posts   1906 Views

Avatar
px

Community Member, 10 Posts

23 November 2009 at 4:58pm

Hi! I'm a newbie in silverstripe and I would just like to ask if how can i add an attribute in a form? For example i want to add onsubmit=''return false;" and class="myClass". Here is the function that I'm using:

public function NewsletterForm() {
      $fields = new FieldSet(
         new EmailField('Email','')
      );
      
      $actions = new FieldSet(
         new FormAction('NewsletterSubmit', 'Ok!')
      );

      $validator = new RequiredFields('Email','onsubmit');
      return new Form($this, 'NewsletterSubmit', $fields, $actions,$validator);
   }

   /**
    * Inserts a submitted email to database
    * @param <type> $form
    */
   public function NewsletterSubmit($form) {
      $newsletter = new Newsletter();
      $newsletter->Email=$_POST['Email'];
      $newsletter->write();
      return Director::redirectBack();
      
      //Director::redirect(Director::currentURLSegment()."?msg=Thank+you+for+signing+up!");
   }

Any help will be much appreciated. Thanks! :)

Avatar
px

Community Member, 10 Posts

24 November 2009 at 3:43pm

it's like having this in form tag:

<form name="frmName" method="post" action="home/newsletterSubmit" class="myClass" onsubmit="return false;">

i just want to add class and onsubmit attributes in this form.

Avatar
dalesaurus

Community Member, 283 Posts

26 November 2009 at 5:51am

To get precise control over your forms I would recommend you extend the form class. This will allow you to override many defaults that "just work" to make subtle changes like you want. See the FormAttributes call.

class NewsletterForm extends Form {
public function __construct($controller, $name) {
$fields = new FieldSet(
new EmailField('Email','')
);

$actions = new FieldSet(
new FormAction('NewsletterSubmit', 'Ok!')
);

$validator = new RequiredFields('Email');

return parent::__construct($controller, $name, $fields, $actions, $validator);
}

public function NewsletterSubmit($form) {
$newsletter = new Newsletter();
$newsletter->Email=$_POST['Email'];
$newsletter->write();
Director::redirectBack();
}

// This is what gets put your form line in Form.ss <form $FormAttributes>
public function FormAttributes() {
$attr = parent::FormAttributes();
// Do your manipulations
$attr .= ' onSubmit="return false;"'
return $attr;
}
}

In your page controller you would herely change your current code to

public function NewsletterForm() {
return new NewsletterForm($this,'NewsletterForm');
}

Hope this helps!