Jump to content
kixe

Hook in Select Dropdown modifies option attributes

Recommended Posts

In a project I had to add the attribute 'disable' to some options of a select field (page reference) to show them but make them unselectable. Since I could not find an integrated solution, I wrote a tiny module and a hook. This could also be a POC to similar needs.

  1. Install module
  2. Add the Module to InputfieldPage in the module settings to make it selectable as Inputfield for page reference fields
  3. Create a hook in ready.php to manipulate attributes of the <option> tag for specified items


Module

<?php namespace ProcessWire;

/**
 * POC Inputfield Select Hook Add Option -- Replacement for InputfieldSelect
 *
 * Selection of a single value from a select pulldown. Same like InputfieldSelect
 * except this version provides hookable addOption() function which allows to modify
 * attributes of the <option> tag (i. e. 'disabled' to show items but disallow to select them
 *
 * @author Christoph Thelen aka @kixe
 *
 */

class InputfieldSelectHookAddOption extends InputfieldSelect {

	/**
	 * Return information about this module
	 *
	 */
	public static function getModuleInfo() {
		return array(
			'title' => __('Select Hookable Add Option', __FILE__), // Module Title
			'summary' => __('Selection of a single value from a select pulldown. Same like InputfieldSelect. except this version provides hookable addOption() function which allows to modify attributes of the <option> tag (e.g. \'disabled\' to show items in dropdown but disallow to select', __FILE__), // Module Summary
			'version' => 100,
			);
	}

	/**
	 * Hook in here to modify attributes
	 */
	public function ___addOptionAttributes($value, $label) {
		return array();
	}

	/**
	 * @see InputfieldSelect::addOption()
	 *
	 */
	public function addOption($value, $label = null, array $attributes = null) {
		if (!is_array($attributes)) $attributes = array();
		$attributes = array_merge($attributes, $this->addOptionAttributes($value, $label));
		return parent::addOption($value, $label, $attributes);
	}
}


Hook

/**
 * This example hook modifies the attributes of the selectable options of a Pagereference field named 'test'.
 * The selectable pages have the template 'test' assigned which includes a checkbox 'disallow'.
 * The attribute 'disabled' will be added to the selectable page if the user does not have the role 'user-extended' and 'disallow' is set.
 *
 */
$wire->addHookAfter('InputfieldSelectHookAddOption::addOptionAttributes', function($e) {
    // quick exit
    if ($e->object->name != 'test') return;
    if ($this->wire('user')->isSuperuser()|| $this->wire('user')->hasRole('user-extended')) return;
    // disable items (pages) in select
    $restrictedPageIDs = $this->wire('pages')->find('template=test,disallow=1')->each('id');
    if (in_array($e->arguments[0], $restrictedPageIDs)) $e->return = array('disabled' => 'disabled');
});    

 

  • Like 4

Share this post


Link to post
Share on other sites
31 minutes ago, zimali said:

That is where I was stuck. It is not populating the default value into the dropdown. The value remains unchanged. I checked the value of $form['egender'] using dpm() and the default_value still showing integer 1. But the dropdown value remains unchanged rather than showing "Female" What am I missing?

ShowBoxKodiLucky Patcher

@zimali. Consider this your final warning. You have been posting Drupal stuff in the ProcessWire forums. You have, presumably,  ignored my request for clarification. This has trolling written all over it. 

  • Like 1

Share this post


Link to post
Share on other sites

We have a lot of selects that are fairly similar so I'd like to have a wrapper for select that encompasses this commonality with data to change the behavior, changing the properties of an object is easier than adding/removing/manipulating html.

Share this post


Link to post
Share on other sites

Since PW >= 3.0.105 you can easily use the following hook.

    $wire->addHookBefore('InputfieldSelect::render', function($e) {
        if ($e->object->name != 'myfield') return; // quick exit if fieldname doesn't match
        $restrictedIDs = array(); // array of option values to be modified, page IDs in case of pagefield
        $optionAttributes = array_fill_keys($restrictedIDs, array('disabled' => 'disabled'));
        $e->object->addOptionAttributes($optionAttributes);
    });

Related commit:
https://github.com/processwire/processwire/commit/07ab8ef9fcefff6a97c688599fb08fb0d462332e#diff-79808b1661a74c0668ee6157537ae478R390

  • Like 2

Share this post


Link to post
Share on other sites
On 10/18/2018 at 11:26 AM, kixe said:

Since PW >= 3.0.105 you can easily use the following hook.


    $wire->addHookBefore('InputfieldSelect::render', function($e) {
        if ($e->object->name != 'myfield') return; // quick exit if fieldname doesn't match
        $restrictedIDs = array(); // array of option values to be modified, page IDs in case of pagefield
        $optionAttributes = array_fill_keys($restrictedIDs, array('disabled' => 'disabled'));
        $e->object->addOptionAttributes($optionAttributes);
    });

Related commit:
https://github.com/processwire/processwire/commit/07ab8ef9fcefff6a97c688599fb08fb0d462332e#diff-79808b1661a74c0668ee6157537ae478R390tv

 

Thank you for the share this commit. 🙂

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 teppo
      This module tracks changes, additions, removals etc. of public (as in "not under admin") pages of your site. Like it's name says, it doesn't attempt to be a version control system or anything like that - just a log of what's happened.
      At the moment it's still a work in progress and will most likely be a victim of many ruthless this-won't-work-let's-try-that-instead cycles, but I believe I've nailed basic functionality well enough to post it here.. so, once again, I'll be happy to hear any comments you folks can provide
      https://modules.processwire.com/modules/process-changelog/
      https://github.com/teppokoivula/ProcessChangelog
      How does it work?
      Exactly like it's (sort of) predecessor, Process Changelog actually consists of two modules: Process Changelog and Process Changelog Hooks. Hooks module exists only to serve main module by hooking into various functions within Pages class, collecting data of performed operations, refining it and keeping up a log of events in it's own custom database table (process_changelog.) Visible part is managed by Process Changelog, which provides users a (relatively) pretty view of the contents of said log table.
      How do you use it?
      When installed this module adds new page called Changelog under Admin > Setup which provides you with a table view of collected data and basic filtering tools See attached screenshots to get a general idea about what that page should look like after a while.
      For detailed installation instructions etc. see README.md.
       


    • By Macaco
      It's a bilingual site. There are two pages: "Artists" and "Events" each with a "Page Reference" field connecting each other.
      - Artists has a field where one can choose events available.
      - Events has a field where you can either choose artists available or create new ones.
      The problems: 
      - When I create an "Artist" page and select events from the list, it doesn't update the collection of participating artists on the "Event" page.
      - When I create an artist from the "Event" page. The field 'artist page > settings > language' is not "Active" for the second language.  When the artist page is created manually,"Active" is on by default.
      I know this all have to do with hooks, but I'm don't fully understand the logics.
    • By Gadgetto
      Status update links (inside this thread) for SnipWire development will be always posted here:
      2019-08-08
      2019-06-15
      2019-06-02
      2019-05-25
      If you are interested, you can test the current state of development:
      https://github.com/gadgetto/SnipWire
      Please note that the software is not yet intended for use in a production system (alpha version).
      If you like, you can also submit feature requests and suggestions for improvement. I also accept pull requests.
      ---- INITIAL POST FROM 2019-05-25 ----
      I wanted to let you know that I am currently working on a new ProcessWire module that fully integrates the Snipcart Shopping Cart System into ProcessWire. (this is a customer project, so I had to postpone the development of my other module GroupMailer).
      The new module SnipWire offers full integration of the Snipcart Shopping Cart System into ProcessWire.
      Here are some highlights:
      simple setup with (optional) pre-installed templates, product fields, sample products (quasi a complete shop system to get started immediately) store dashboard with all data from the snipcart system (no change to the snipcart dashboard itself required) Integrated REST API for controlling and querying snipcart data webhooks to trigger events from Snipcart (new order, new customer, etc.) multi currency support self-defined/configurable tax rates etc. Development is already well advanced and I plan to release the module in the next 2-3 months.
      I'm not sure yet if this will be a "Pro" module or if it will be made available for free.
      I would be grateful for suggestions and hints!
      (please have a look at the screenshots to get an idea what I'm talking about)
       




    • By apeisa
      Update 31.7.2019: AdminBar is now maintained by @teppo. Modules directory entry has been updated, as well as the "grab the code" link below.
      ***
      Latest screencast: http://www.screencas...73-ab3ba1fea30c
      Grab the code: https://github.com/teppokoivula/AdminBar
      ***
      I put this Adminbar thingy (from here: http://processwire.c...topic,50.0.html) to modules section and to it's own topic.
      I recorded quick and messy screencast (really, my first screencast ever) to show what I have made so far. You can see it from here: http://www.screencas...18-1bc0d49841b4
      When the modal goes off, I click on the "dark side". I make it so fast on screencast, so it might seem a little bit confusing. Current way is, that you can edit, go back to see the site (without saving anything), continue editing and save. After that you still have the edit window, but if you click "dark side" after saving, then the whole page will be reloaded and you see new edits live.
      I am not sure if that is best way: there are some strengths in this thinking, but it is probably better that after saving there shouldn't be a possibility to continue editing. It might confuse because then if you make edits, click on dark side -> *page refresh* -> You lose your edits.
      ***
      When I get my "starting module" from Ryan, I will turn this into real module. Now I had to make some little tweaks to ProcessPageEdit.module (to keep modal after form submits). These probably won't hurt anything:
      if($this->redirectUrl) $this->session->redirect($this->redirectUrl); if(!empty($_GET['modal'])) $this->session->redirect("./?id={$this->page->id}&modal=true"); // NEW LINE else $this->session->redirect("./?id={$this->page->id}");   and...
      if(!empty($_GET['modal'])) { $form->attr('action', './?id=' . $this->id . '&modal=true'); } else { $form->attr('action', './?id=' . $this->id); // OLD LINE }  
×
×
  • Create New...