fbg13

FieldtypeOptions - set selectable options through api

Recommended Posts

I'm setting up some fields in a module and i need an options field, but i can't figure out how to set its options with the api.

These options:

Untitled.jpg

Share this post


Link to post
Share on other sites

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();
	}
}

 

Share this post


Link to post
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.

Share this post


Link to post
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 4

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

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!

 

Share this post


Link to post
Share on other sites

Have you tried like this:

$options = "1=option1|Option 1\n2=option2|Option 2\n3=option3|Option 3";

BTW - I haven't tested this, just going on what is exported when exporting the field.

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

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 4

Share this post


Link to post
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


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By prestoav
      Hi folks,
      I have a marketplace site built on PW which I'd like to tie to a subscription payment system for those selling. The user accounts currently use specific PW user accounts. I'm looking closely at PayWhirl to manage payments and subscriptions as it looks ideal for subscriptions. Their API seems to work well too from initial testing.
      I wondered if anyone else in this super forum had used PayWhirl and had any advice or tips & tricks?
      Thanks.
      https://app.paywhirl.com/
    • By Harmen
      Hello all,
      Was wondering if any of you tried to include the Exact PHP client by Picqer in Processwire (URL)? I am trying to at the moment but I am stuck at the Authorization process. Building it inside a module file to execute a certain function every 6 hours to update something on the website. For the authorization process the file has to execute the following piece of code:
      header('Location:'. $urlThatRedirectsMeToTheLoginOfExact); But each time I am trying  to do so, I get the following error: Cannot modify header information - headers already sent by (output started at /processwire/index.php:55). I am out of options so that's why I am trying to find someone who used this library and could get it to work or someone who knows how I can fix it.
      Tips are highly appreciated (if they work ;))
      Cheers, Harmen
    • By noelboss
      Short description of the issue
      Since PW 3.0.88: When I try to retrive a croped file using the api filesManager() and it's basename, I get the original version instead of the croped variation.
      Expected behaviour
      Looking up a variation using the path and filesManager should return the variation file.
       $page->filesManager->getFile("/path/to/filebasename.400x400.jpg"); // $file->basename > filebasename.400x400.jpg Actual behavior
      The variation is returned.
       $page->filesManager->getFile("/path/to/filebasename.400x400.jpg"); // $file->basename > filebasename.jpg  
      » Is this a bug or do I miss something here?
       
      Code:
      dump($page->filesManager->path.$input->get->filename('f')); $file = $page->filesManager->getFile($page->filesManager->path.$input->get->filename('f')); dump($file); dump($page->filesManager->path.$file->basename); Output:
      "/home/ubuntu/workspace/www/site/assets/files/-1579/colin-rex-434063.400x400.jpg" (79) ProcessWire\Pageimage #796f pageimages protected => ProcessWire\Pageimages #d195 original protected => ProcessWire\Pageimage #796f { RECURSION } variations private => null imageInfo private => array (2) width => 0 height => 0 error protected => "" pagefiles protected => ProcessWire\Pageimages #d195 data protected => array (6) basename => "colin-rex-434063.jpg" (20) description => "" tags => "" formatted => true modified => 1516025386 created => 1516025386 useFuel protected => true _instanceNum private => 870 localHooks protected => array () trackChanges private => 2 changes private => array (1) formatted => array (1) 0 => null _notices protected => array (3) errors => null warnings => null messages => null _wire protected => ProcessWire\ProcessWire #28d0 in .../www/site/templates/app/utils/download.php:29
      "/home/ubuntu/workspace/www/site/assets/files/-1579/colin-rex-434063.jpg" (71)
    • By cosmicsafari
      Hi all,
      Im a bit confused by an issue I have come across today.
      I have a module which connects to a third party (once an hour using LazyCron), parses a publicly available XML file, turns it into useable information which I then use the API to save as PW Pages.
      On the whole this has been working great however today I noticed that it kept failing on one of the imports.
      After doing some investigation I realised its appears to be dying at the save page stage.
      From the documentation $page-save() should return either True/False, so I thought I would update the code to reflect this while debugging.
      $this->log(1); $bool = $p->save(); if($bool){ $this->log('Saved successfully'); } else { $this->log('Fail to save'); } $this->log(2); However the script only gets to the save() part and then appears to terminate. Then when checking the error log the latest entry is always just '1'
      Any ideas as i'm a tad confused why I at least don't get a response of some kind?
       
       
       
    • By iNoize
      Hello, 
      for an Project i need help for an Script. 
      There is an XML File with all the Objects Data and Images for every object. 

      This is the Data Structure 
      http://prntscr.com/hvfo31


      One XML file and Pictures. 
      So every Time the new Data is Uploadet via ImmoTool there have to be maybe an batch or something or an button in the Sitebackend to check the new files. 

      If the Status is  NEW then create an Object 
      if the Status is CHANGE  then make some changes 
      If the Status is Delete then remove the Object in other Parent 

      There are Basic infos in XML like Description Rooms etc. 
      Also the latitude and attitude for the maps. 
      After succsessful changes the Folder schould be empty for the next upload. 

      I need only help to create and handle the sites with some data (PW API ). The output I will generate by myself. 


      I have some basic php code 

      Need somebody to fix it ready for me in PW. 

      Tnx