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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

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

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

Only allow 20 characters for Varchar in admin area


Go to End


4 Posts   2214 Views

Avatar
DeklinKelly

Community Member, 197 Posts

26 May 2009 at 1:34am

In a tab, there is a Varchar field that I want to contain a maximum of 20 characters.

<input type="text" maxlength="20" />

<?php
class IndexPage extends Page {
   static $db = array(
      'Banner1Title' => 'Varchar''
   );

   static $has_one = array(
   );
	
   function getCMSFields() {
      $fields = parent::getCMSFields();
      $fields->addFieldToTab("Root.Content.Banner", new TextField('Banner1Title','Banner 1 Title'));
      return $fields;
   }
}
 
class IndexPage_Controller extends Page_Controller {
}
?>

Avatar
PGiessler

Community Member, 47 Posts

26 May 2009 at 3:29am

Hi hknight,

if you want to set a maximum of 20 characters. You have to use this source code:

<?php
class IndexPage extends Page {
static $db = array(
'Banner1Title' => "Varchar(20)"
);

...

Best regards,

Pascal

Avatar
bummzack

Community Member, 904 Posts

26 May 2009 at 3:40am

What PGiessler posted is not entirely correct.
This would only change the amount of characters allowed in your DB Field. AFAIK this will not put any restriction on your TextField, therefore it would be possible to enter more than 20 characters, but only 20 would be stored in the Database.

To limit the characters on a TextField, pass the max number of characters as 4th parameter to the TextField Constructor. Eg.

/*
1) field-name
2) title
3) value
4) max-length
*/
new TextField('Banner1Title', 'Banner 1 Title', '', 20);

Having a look at the source or API Docs would help in these cases...

Avatar
PGiessler

Community Member, 47 Posts

26 May 2009 at 11:50pm

Hi banal,

thank you for your post. Your approach is the right one. First of all you have to put restrictions on the textfield and then you can put this in the database. But I think, you doesn't need the restrictions in the database; at most for security reasons.

Best regards,

Pascal