Jump to content

using Page field with API in the front end


seddass
 Share

Recommended Posts

Hi all, 

Hope for a helpful hint and thank you in advance. 

I am trying to create a form in the frontend with custom markup for the form and the fields. Its all fine, except that I cant find out

1. how to remove the empty "<option></option>" choice and

2. I was wandering if there is a smarter way of making one of the options "selected" in page field using select inputfield. 

Here is my code:

$newPage = new Page();
$newPage->template = 'my_weather';

$field = $fields->get('temp_units');
$inputfield = $field->getInputfield($newPage);
$select = $inputfield->getInputfield();
$options = $select->getOptions();
foreach ($options as $key => $val){
      $select->removeOption($key);
}
            
foreach ($options as $key => $val){
      $attr = ($val == 'kg') ? array('selected' => 'selected') : null; 
      $select->addOption($key, $val, $attr);
}

echo $select->render();

Of course, I could skip render() and output my markup with the options above instead, but it is a quite large form and I prefer to know if this is the right way of getting things done with the API. 

Thanks!

Link to comment
Share on other sites

You may want to set $select->required = true; so that there isn't an unselected option. Rather than removing all the options and adding them back, you should just be able to set the 'value' attribute to whatever you want the selected option to be:

$select->attr('value', $selected_page_id); 

Note that "kg" is your label rather than the value, so you are going to know the ID of the page with name/title "kg" in order to make it selected. 

  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...