Jump to content
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 7

Share this post


Link to post
Share on other sites

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!

 

 

 

 

 

 

 

Share this post


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

Share this post


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

Share this post


Link to post
Share on other sites

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?

Share this post


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

Share this post


Link to post
Share on other sites

Or use the option manager with a fixed string, something like this:

$field->save();   // save field first
$manager = new \ProcessWire\SelectableOptionManager();
$manager->setOptionsString($field, __("Yes\nNo"), true);
$field->save();

 

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By louisstephens
      So I was tinkering around with the "select fields" field type and added it to a repeater. My thoughts were I could have a user select a field (textarea, text, etc etc) that I defined and give it a name (another field in the repeater) and create their own form on the page. To be honest, I am now a little lost with rendering the form and mailing the results as potentially the form will be unique and custom every time.  The only way I know to handle the output is by going about it this way:
      $forms = $page->form_select_fields; foreach($forms as $form) { if($form->name === "form_input") { //output input with custom name } elseif($form->name === "form_textarea") { //output input with custom name } } Is there a better way to go about rendering the elements from the repeater? As far as the custom sending goes, I am really at a loss since it would be pretty dynamic. Has anyone used this type of approach, and if so, how did you handle this without going insane?
    • By Harmen
      I want to add a few pages to an AsmSelect Page field inside a repeater using the following code:
      $trialsPage = wire("pages")->get(28422); // Get the page $trialsPage->of(false); $newTrial = $ordersPage->trial_repeater_orders->getNewItem(); // Add item to repeater foreach ($selectedProducts as $selectedProduct){ $productPage = $pages->get("template=product, reference=$selectedProduct"); $newTrial->trial_selected_products->add($productPage); } $newTrial->save(); $trialsPage->save(); However, when I check the page where the field is located it doesn't have the new values as expected. The selected pages exist, the field is in the right location, made sure that the output formatting is turned off: $page->of(false); But it still doesn't work with a variable. No matter what I try, it doesn't work.
      It only works when I replace $selectedProduct with a hardcoded string. Am I doing something wrong here?
    • By louisstephens
      So I have been diving into hooks lately, and I am enjoying them thus far. However, I guess I am a bit stumped on how to achieve what I want too. I am trying to set up a hook that would create a new child page when the parent page is saved. However, when you save the parent page a second time, I just need to update the child page without creating multiple child pages. What would be the best way to go about this?
      So after rereading my post, I believe it is a bit vague so I will try to explain more. 
      The Goal:
      Create a page with a template "one". Once the page is created/saved => create a new child page with the template of "two" If the parent is saved anytime after, do nothing to the child page (limit the parent page to one child page) The parent page is really just being used to output content, whereas the child page is being used to pull out the some fields from the parent to be used elsewhere. I might have made this too complicated in my head.
    • By Peter Knight
      Is there a way to make JPGs progressive by default via the API?
      I've added the following to my site/config.php file but user-uploaded images are often displayed as non progressive.
      $config->imageSizerOptions = array( 'upscaling' => true, // upscale if necessary to reach target size? 'cropping' => true, // crop if necessary to reach target size? 'autoRotation' => true, // automatically correct orientation? 'interlace' => true, // use interlaced JPEGs by default? (recommended) 'sharpening' => 'soft', // sharpening: none | soft | medium | strong 'quality' => 95, // quality: 1-100 where higher is better but bigger 'hidpiQuality' => 60, // Same as above quality setting, but specific to hidpi images 'defaultGamma' => 0.5, // defaultGamma: 0.5 to 4.0 or -1 to disable gamma correction (default=2.0) ); Thanks
    • By louisstephens
      From my last post, I was given a good idea on how to count the repeater items, and it worked wonderfully. I got my code working well and the columns (based on the count) all work well as well. Now, I have a head scratcher on my hands. 
      <?php $buttonsIncluded = $page->special_custom_buttons->find('special_custom_buttons_include=1'); $buttonsIncludedCount = count($buttonsIncluded); $buttonsIncludedCountAdditional = $buttonsIncludedCount +1; echo $buttonsIncludedCount; ?> <div class="row"> <?php foreach($buttonsIncluded as $button): ?> <?php if($button->custom_buttons_include): ?> <?php if($buttonsIncludedCountAdditional == 2): ?> <div class="col-6"> <a href=""><?php echo $button->custom_buttons_text; ?></a> </div> <?php elseif($buttonsIncludedCountAdditional == 3): ?> <div class="col-4"> <a href=""><?php echo $button->custom_buttons_text; ?></a> </div> <?php elseif($buttonsIncludedCountAdditional == 4): ?> <div class="col-3"> <a href=""><?php echo $button->custom_buttons_text; ?></a> </div> <?php endif; ?> <?php endif; ?> <?php endforeach; ?> </div> All of this is included in a larger foreach statement that is pulling in other data (like body copy etc etc) from a Page Table field. As you can see in my code above, I am adding "1" to the count, so I can have space in the grid layout for a new button.
      So, right now: it looks something like: 
      [repeater button] [repeater button] [repeater button] [space for new button] What I really need to do is to pull in the button from the Page Table and add it into the new space so it looks like:
      [repeater button] [repeater button] [repeater button] [button from Page Table] Is this even possible todo, or is there a better way to go about this? 
       
      *Edit*
      So, I really just overlooked something quite easy here. Since the grid is based on 12 columns, I could just take 12 and divide by $buttonsIncludedCountAdditional which would give me the remaining col width to use outside the foreach loop. I was trying to make this too complicated.
×
×
  • Create New...