Jump to content

Loading field options into inputfieldSelect


Marcel Stäheli
 Share

Recommended Posts

I added some fields to the user template. Among them is a single select field named "country" with a few country names in english and german.
If logged in, the user has access to his profil page on the frontend where the fields that he is allowed to change are displayed in a form using the form API.

I want to populate the select field with the same options as the field has in the backend. But I can't get it to work:

//Getting all Options
$fieldCountry = $fields->get('country');
$all_options = $fieldCountry->type->getOptions($fieldCountry)->getValues();

//Creating the field
$field = $modules->get("InputfieldSelect");
$field->label = _("Country");
$field->addOptions($all_options);    
$field->set('initValue', $user->country->title);
$form->append($field);

Something about the selector for the options is wrong. I got the code from the Select Option Fieltype Page but it didn't work with  $field->addOptions(). So I added ->getArray() myself. Now I have a dropdown list on the front end but it's just the numbers instead of the country names.

Also I would like the currently chosen country to be the preselected option, So  when the form gets saved without any new input, the country doesn't change. How would I do that? My code doesn't work.

Link to comment
Share on other sites

To add the 'country' field you can simply do this:

$inputfield = $user->getInputfields('country');
$form->add($inputfield);

Depending on how many fields in your user template, when building a profile edit form for the frontend it can be easier to define an array of 'ignore' fields and then add all inputfields for the user template that are not in the ignore array. Pretty sure I got this idea from some code by @Soma.

// Get the fields from the user template
$inputfields = $user->getInputfields();
// Don't include these fields in the form
$ignore_fields = [
    'user_name',
    'temp_password',
    'roles,'
];
// Add the inputfields to the form
foreach($inputfields as $inputfield) {
    if(in_array($inputfield->name, $ignore_fields)) continue;
    $form->add($inputfield);
}

 

  • Like 3
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

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...