I have a default value set in $db array to "1". For ex :
class Page extends SiteTree {
public static $defaults = array(
"Indexing" => "1"
);
}
This works fine and sets the default value very nicely. Now I have a different page type say for example :
class mypage extends page{
// Since this class extends page so it will take the default
// value "Indexing" => "1" ..
}
I want to set the default value "Indexing" => "0" in the "mypage" page type. How can I achieve that.
I have tried the following :
class mypage extends page{
public static $defaults = array(
"Indexing" => "0"
);
}
This does not work as the parent default value is set. Any help would be deeply appreciated. Thanks.
@Zauberfisch is almost to the point but I think he missed something. You must use :
public function populateDefaults(){
if($this->ClassName == "mypage")
$this->PGIndexing = "0";
else
$this->PGIndexing = "1";
}
Here you are setting the default value based on the classname. So this should work. Cheers :)
obviously this will error, because $db is not for setting values, it is the database definition of silverstripe.
if it works without an error then you either have not pasted the complete code, or there is a bug in silverstripe that lets you get a way with this faulty syntax.
either way, her is how its done:
class Page extends SiteTree {
// public static for SilverStripe 3.x, private static for 3.1+
public static $db = array(
"Indexing" => "Int",
);
public static $defaults = array(
"Indexing" => 1,
);
}
now that was the base class, for the child class, I am not a 100% sure that overwriting the default value actually works, but give it a try, if it doesn't, you have to overwrite the populateDefaults
method and set it there.
class OtherPage extends Page {
public static $defaults = array(
"Indexing" => 2,
);
}
alternatively, if that does not work, you have to overwrite populateDefaults
as mentioned above.populateDefaults
is the method that usually reads the $defaults variable and sets some system defaults.
class OtherPage extends Page {
public function populateDefaults() {
$return = parent::populateDefaults();
$this->Indexing = 2;
return $return;
}
}
note, that in all cases ($defaults
and populateDefaults()
) it is ONLY run when the record is FIRST CREATED.
this also means that if you already have a record, and you add a field like Indexing later on, it will NOT effect existing records, those will have a value of NULL, 0, empty string and so on depending on the data type.