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   1499 Views

Avatar
NtM

Community Member, 39 Posts

11 December 2009 at 12:08pm

Edited: 11/12/2009 1:47pm

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

Forum Moderator, 5513 Posts

11 December 2009 at 7:51pm

Edited: 11/12/2009 7:52pm

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

Community Member, 39 Posts

12 December 2009 at 6:00am

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

Forum Moderator, 5513 Posts

12 December 2009 at 9:44am

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

Community Member, 39 Posts

12 December 2009 at 12:17pm

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