Jump to content

FieldtypeOptions - set selectable options through api


fbg13
 Share

Recommended Posts

I also found the same problem for adding FieldtypeOptions through API. Below are the codes that I'm using which is work well for other field types.

From the json export the FieldtypeOptions array value is in this line "export_options": {"default": "1=on|On\n2=off|Off\n3=indexon|Index On\n4=indexoff|Index Off"}

 

public function extraFields() {
	$fields = array(
		'invoice_stat' => array('id'=>'112', 'type'=>'FieldtypeOptions', 'flags'=>'0', 'name'=>'invoice_stat', 'label'=>'Status', 'description'=>'', 'derefAsPage'=>'1', 'collapsed'=>'0', 'columnWidth'=>'', 'parent_id'=>'', 'template_id'=>'', 'findPagesSelector'=>'', 'labelFieldName'=>'.', 'inputfieldClass'=>'InputfieldSelect', 'usePageEdit'=>'0', 'labelFieldFormat'=>'{pg_alias}', 'tags'=>'', 'allowUnpub'=>'', 'showIf'=>'', 'required'=>'', 'requiredIf'=>'', 'findPagesCode'=>'', 'defaultValue'=>'1=on|On\n2=off|Off\n3=indexon|Index On\n4=indexoff|Index Off', 'addable'=>''),		
	);
	
	
	foreach ($fields as $field) {
		$f = new Field();
		$f->type = $this->modules->get($field['type']);
		//$f->id = $field['id'];
		$f->name = $field['name'];
		$f->label = $field['label'];
		
		if (isset($field['inputfieldClass'])) $f->inputfieldClass = $field['inputfieldClass'];
		if (isset($field['inputfield'])) $f->inputfield = $field['inputfield'];
		if (isset($field['export_options'])) $f->export_options = $field['export_options'];
		
		if (isset($field['flags'])) $f->flags = $field['flags'];
		if (isset($field['description'])) $f->description = $field['description'];
		if (isset($field['notes'])) $f->notes = $field['notes'];
		if (isset($field['derefAsPage'])) $f->derefAsPage = $field['derefAsPage'];
		if (isset($field['collapsed'])) $f->collapsed = $field['collapsed'];
		if (isset($field['parent_id'])) $f->parent_id = $field['parent_id'];
		if (isset($field['labelFieldName'])) $f->labelFieldName = $field['labelFieldName'];
		
		if (isset($field['tags'])) $f->tags = $field['tags'];
		if (isset($field['allowUnpub'])) $f->allowUnpub = $field['allowUnpub'];
		if (isset($field['showIf'])) $f->showIf = $field['showIf'];
		if (isset($field['columnWidth'])) $f->columnWidth = $field['columnWidth'];
		if (isset($field['required'])) $f->required = $field['required'];
		if (isset($field['requiredIf'])) $f->requiredIf = $field['requiredIf'];
		if (isset($field['template_id'])) $f->template_id = $field['template_id'];
		if (isset($field['findPagesSelector'])) $f->findPagesSelector = $field['findPagesSelector'];
		if (isset($field['findPagesCode'])) $f->findPagesCode = $field['findPagesCode'];
		if (isset($field['labelFieldFormat'])) $f->labelFieldFormat = $field['labelFieldFormat'];
		if (isset($field['defaultValue'])) $f->defaultValue = $field['defaultValue'];
		if (isset($field['addable'])) $f->addable = $field['addable'];

		$f->save();
	}
}

 

Link to comment
Share on other sites

What is $field['export_options'] supposed to be?

Just the value from export_options of the export json?

$f4 = new Field();
$f4->type  = $this->modules->get("FieldtypeOptions");
$f4->name  = "name";
$f4->label = "Label";
$f4->export_options  = "1=on|On\n2=off|Off\n3=indexon|Index On\n4=indexoff|Index Off";
$f4->save();

I tried multiple formats but there are no options after i install the module.

Link to comment
Share on other sites

The methods for setting new options for an Options field via the API seem to be a bit convoluted - I think it's probably an oversight and it would be worth raising a feature request at GitHub.

There's a method that seems to be primarily intended for the admin back-end: setOptionsString(). You can use it but the way the options are defined (string with line break separator) is a bit weird for API use and it's not easy to get it to play nicely with existing options.

$f = $fields->my_options_field;
$manager = new SelectableOptionManager();
$options = 'red
green
blue'; // you can also set IDs and values if needed
$manager->setOptionsString($f, $options, false); // if last argument is omitted/true you will remove any existing options

Otherwise you could manually create SelectableOption objects, add them to a SelectableOptionArray, and use addOptions(), deleteOptions(), setOptions(), etc, with that SelectableOptionArray. See the module source code. It's hardly a simple process though.

I think what's needed are methods to go from options to PHP array and PHP array to options.

  • Like 5
Link to comment
Share on other sites

$f4 = new Field();
$f4->type  = $this->modules->get("FieldtypeOptions");
$f4->name  = "name";
$f4->label = "Label";
$f4->save();
$manager = new SelectableOptionManager();
$options = 'red
green
blue'; // you can also set IDs and values if needed
$manager->setOptionsString($f4, $options, false);
$f4->save();

That did it, had to save the field before adding the options, took me a while to figure it out.

Thanks for the help.

  • Like 3
Link to comment
Share on other sites

  • 2 months later...

I have this string of options:

option1|Option 1
option2|Option 2
option3|Option 3

I add the options string like mentioned before:

$manager = new \ProcessWire\SelectableOptionManager();
$manager->setOptionsString($field, $options, true);

The result is this:

Screen Shot 2017-01-04 at 13.37.52.png

If I add it with IDs

1=option1|Option 1
2=option2|Option 2
3=option3|Option 3

The result is this:

Screen Shot 2017-01-04 at 13.40.45.png

In both cases within the field settings detail tab, everything looks OK, and the preview shows the expected output:

Screen Shot 2017-01-04 at 14.15.45.png

 

Also: Changing the override argument to false, does not affect this behavior.

In the database, everything looks fine:

Screen Shot 2017-01-04 at 14.33.01.png

 

Debugging $inputfield->options in FieldtypeOptions:getInputfield, the options array looks fine as it should: Three items with an id, value and title.

This is VERY weird:

If I replace the return value in FieldtypeOptions:getInputfield

// original
return $inputfield;

// replace
$fs = $this->modules->get('InputfieldFieldset');
$fs->add($inputfield);
return $fs;

I get the correct output, in the given Fieldset:

Screen Shot 2017-01-04 at 14.50.04.png

This suggests that the misbehavior is happening somewhere else?

 

If I create it via admin, everything works as expected, only the titles show.

Any help? Thanks!

 

Link to comment
Share on other sites

Got it working. The source of the misbehavior was, that I set the string somewhere else afterwards, like so: $field->options = $optionsString;

Doh! The side effects are still very strange though, and interesting that the field class even uses it somehow.

Link to comment
Share on other sites

  • 1 year later...

I've been working with FieldtypeOptions recently and in the absence of documentation thought I would share some example code:

$field = $fields->get('test_options');
/* @var FieldtypeOptions $fieldtype */
$fieldtype = $field->type;

// Get existing options
// $options is a SelectableOptionsArray (WireArray)
// If there are no options yet this will return an empty SelectableOptionsArray
$options = $fieldtype->getOptions($field);

// Create an option
$yellow = new SelectableOption();
$yellow->title = 'Yellow';
$yellow->value = 'yel'; // if you want a different value from the title
// Don't set an ID for new options - this is added automatically
// Will deal with 'sort' property later

// Create another option
$orange = new SelectableOption();
$orange->title = 'Orange';

// Add option after the existing options
$options->add($yellow);

// Get an option by title
$green = $options->get('title=Green');

// Insert option at a certain position
$options->insertAfter($orange, $green);

// Remove an option
$options->remove($green);

// Reset sort properties (so order of options is the same as the SelectableOptionsArray order)
$sort = 0;
foreach($options as $option) {
    $option->sort = $sort;
    $sort++;
}

// Set options back to field
$fieldtype->setOptions($field, $options);

 

  • Like 10
Link to comment
Share on other sites

  • 3 weeks later...

Hi @Robin S,

I try to echo an multiple options inside a class name. I can do using:

$field = $fields->get('test_options'); or  $fieldtype = $field->type; 
I use this: <div class="mix <?= $product->category_4->title ?>">

  But I have multiple selection, and in this way the show me only the first option I check in the page in the backend.

 

I have try to use : $options = $fieldtype->getOptions($field);  But I not have understand  how to make it work inside my code:

<?php foreach($page->children() as $product): ?>
        <?php
          $image_sta = $product->img_statica->first;
        ?>
          <div class="mix <?= $product->category_4->title ?>">
              <img src="<?= $image_sta->url; ?>">
            	<h3><a href="<?=$product->url;?>"><?= $product->title; ?></a></h3>
          </div>
      <?php endforeach; ?>

Every time i try differente code he give me always the first option name.  If I don't use the ->title this returns to me with all ID, but I can not use this ID I have to use the name of the options fields. I can do it?

Thanks!

 

 

 

 

 

 

 

Link to comment
Share on other sites

@MarcoPLY, this topic is about setting the selectable options for a field via the API. As far as I can see your question isn't related to that so would be better asked in a new topic.

If you have a "multiple values" options field you cannot simply echo the field value. You have to loop over the field value in a foreach() or perhaps use implode() to create a string from the value.

Here is one way you could try:

<?php foreach($page->children() as $product): ?>
    <?php
    $image_sta = $product->img_statica->first;
    $classes = '';
    foreach($product->category_4 as $option) $classes .= " $option->title";
    ?>
    <div class="mix<?= $classes ?>">
        <img src="<?= $image_sta->url; ?>">
        <h3><a href="<?= $product->url; ?>"><?= $product->title; ?></a></h3>
    </div>
<?php endforeach; ?>

Also check out the documentation for the Select Options fieldtype.

  • Like 1
Link to comment
Share on other sites

Hi @Robin S sorry for going out of topic, next time I'll do a new one topic.

Thank you for your answer! It's a great help! I still have to learn a lot about how to use the api in pw (and also php!!) :) 
I read the documentation and it helped me, only that for the multiple options I was a bit confused, but now I understand how it works! So thank you a lot!

Link to comment
Share on other sites

  • 1 year later...

I try to create a new FieldtypeOptions field and set some options for it, but the options don't appear. What am I doing wrong?

$old_field = $fields->get('abzuege_neu');
if ($old_field){
$fields->delete($old_field);    
}

$ja = new SelectableOption();
$ja->title = 'Ja';
$ja->value = 'Ja';

$nein = new SelectableOption();
$nein->title = 'Nein';
$nein->value = 'Nein';

$fieldtype = $this->modules->get("FieldtypeOptions");

$field = new Field();
$field->type  = $fieldtype;
$field->inputfieldClass = 'InputfieldRadios';
$field->optionColumns = true;
$options = $fieldtype->getOptions($field);
d($options, "existing options");

$options->add($ja);
$options->add($nein);
$options->pop(1); // remove the first default option
d($options, 'SelectableOptionArray');


$field->name  = "abzuege_neu";
$field->label = "Abzüge";
// $field->_options = "1=option1|Option 1\n2=option2|Option 2\n3=option3|Option 3";
$fieldtype->setOptions($field, $options);
$field->save();
d($field);

My code can be easily be executed via Tracy console.

@Robin S Maybe you can provide some help?

Link to comment
Share on other sites

The trick is to set the options AFTER saving the field, otherwise they seem to be overwritten with an empty value.
 

$old_field = $fields->get('abzuege_neu');
d($old_field, 'Field exists');
if ($old_field){
$fields->delete($old_field);    
}

$ja = new SelectableOption();
$ja->title = 'Ja';
// $ja->value = 'Ja'; // only if this should be different from title

$nein = new SelectableOption();
$nein->title = 'Nein';
// $nein->value = 'Nein'; // only if this should be different from title

$fieldtype = $this->modules->get("FieldtypeOptions");

$field = new Field();
$field->type  = $fieldtype;
$field->inputfieldClass = 'InputfieldRadios';
$field->optionColumns = true;
$field->name  = "abzuege_neu";
$field->label = "Abzüge";
$field->save();

// Now add the options to the field
$options = $fieldtype->getOptions($field);
d($options, "existing options");

$options->removeAll();
$options->add($ja);
$options->add($nein);

d($options, 'SelectableOptionArray');

// $manager = new SelectableOptionManager();
// $managerOptions = 'option1|Option 1
// option2|Option 2
// option3|Option 3
// '; // you can also set IDs and values if needed
// $manager->setOptionsString($field, $managerOptions, false);

$fieldtype->addOptions($field, $options);

d($field);

 

  • Like 1
Link to comment
Share on other sites

  • 1 year later...

this is very helpful. I use this to create some select options for a module Iam working on.
However this creates a blank option as the first option. How can I remove the first blank option?

$this->manager = new \ProcessWire\SelectableOptionManager();
$options = 'Manual 
Auto';
$this->manager->setOptionsString($field, $options, true);
$field->save();

 

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...