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.

Template Questions

new TreeDropdownField returns id of the page


Reply

5 Posts   1430 Views

Avatar
NtM

11 December 2009 at 12:08pm (Last edited: 11 December 2009 1:47pm), Community Member, 39 Posts

Here is y code:

static $db = array(
      'Bucket1_Link' => 'Text',
   );
public function getCMSFields()
   {
      $fields = parent::getCMSFields();   
      $fields->addFieldToTab('Root.Content.Bucket1', new TreeDropdownField('Bucket1_Link', 'Choose a page', 'SiteTree'));
return $fields;
}

in the template I use the variable $Bucket1_Link, whhich is id of the page. But I need the URL of the page. How would I get it?
thank you!

Avatar
Willr

11 December 2009 at 7:51pm (Last edited: 11 December 2009 7:52pm), Forum Moderator, 5511 Posts

Well for TreeDropdownFields you normally save the field as a 'relationship' with a page. Change the

static $db = array(
'Bucket1_Link' => 'Text',
);

To a $has_one

static $has_one = array(
'Bucket1' => 'SiteTree',
);

And slight tweak to your getCMSFields...

$fields->addFieldToTab('Root.Content.Bucket1', new TreeDropdownField('Bucket1_Link', 'Choose a page', 'SiteTree'));

Change to

$fields->addFieldToTab('Root.Content.Bucket1', new TreeDropdownField('Bucket1ID', 'Choose a page', 'SiteTree'));

Rebuild your database and refresh the page, resave the value then in the template you can now use $Bucket1 as a Page object so you can do $Bucket1.Link

Avatar
NtM

12 December 2009 at 6:00am Community Member, 39 Posts

Thanks a lot!

I did like this:

in the control of the page I defined a function:

public function page_url_by_id_bucket1(){
      $pageID = $this->Bucket1_Link;
    $obj = DataObject::get_by_id('SiteTree', $pageID);
      $URL = $obj->URLSegment;
      return $URL;
}

and in the template I write:

"<a href="$page_url_by_id_bucket1">Link</a> "

Avatar
Willr

12 December 2009 at 9:44am Forum Moderator, 5511 Posts

Thats the other way you can do it :) usually in SS we prefer passing around relationships and objects rather then just strings as its alot more flexible.

Watch out in your version - if $this->Bucket1_Link gets unset (eg a client or someone doesn't set it) that function will throw a error as it won't be able to get the $obj then you're calling $obj->URLSegment on it. You'll need to add a check to make sure $obj exists before calling any methods on it.

Avatar
NtM

12 December 2009 at 12:17pm Community Member, 39 Posts

The only problem with your method is that it doesn't save the selected page from the tree. It always shows the message "(Choose)"