Jump to content

Determine via API if page is loaded in ProcessWire panel?


Gadgetto
 Share

Recommended Posts

In my Process module I'd like to load some processes (___executeSomething1, ___executeSomething2, ...) in PW Panels. If those pages are loaded in panel, I'd like to hide some interface parts (like WireTabs). The question is, is it possible to determine via API if a page is loaded inside a panel? Or do I need to use jQuery?

Link to comment
Share on other sites

hmm, the iframe looks in my PW install like this:

<iframe class="pw-panel-content" src="../setup/manual/?modal=panel&amp;pw_panel=1"></iframe>

If you work with JS, you could also check for body class "modal".

  • Like 1
Link to comment
Share on other sites

43 minutes ago, dragan said:

hmm, the iframe looks in my PW install like this:

<iframe class="pw-panel-content" src="../setup/manual/?modal=panel&amp;pw_panel=1"></iframe>

If you work with JS, you could also check for body class "modal".

Ah ok - it was "pw_panel" not "panel".

Thanks, it works now!

Link to comment
Share on other sites

7 minutes ago, bernhard said:

sorry, of course it was


?modal=panel

The pw_panel get param is new to me - what does it do exactly?

 

I also don’t know. ;) Didn’t even know there are Params set...

Do you think I should use the modal=panel param instead of pw_panel=1?

Link to comment
Share on other sites

What the others have said. In addition, note that you can use your own param string when you build your modal URL and check that instead. However, I have found that param strings are not as reliable as url segments. I tend to use the latter more. For instance, for my process module's modal landing pages, I append some pre-determined url segments and check that instead. Below, some rough examples of both approaches (untested, mostly written from memory :-)).

// using custom param string (popup)
$url = $this->wire('config')->urls->admin . "your-process-module-name/some-page/?modal=1&popup=1/";
$input = $this->wire('input');

if((int)$input->get->popup == 1){
    // in modal
}

// OR using custom url segment (popup)

// create URL with segment
$url = $this->wire('config')->urls->admin . "your-process-module-name/some-page/popup/";
$input = $this->wire('input');
if($input->urlSegment2 && $input->urlSegment2 == 'popup') {
    // we are in a modal
}
else {
    // not in a modal
}

Something along those lines...

  • Like 1
Link to comment
Share on other sites

On 8/6/2019 at 9:57 PM, kongondo said:

What the others have said. In addition, note that you can use your own param string when you build your modal URL and check that instead. However, I have found that param strings are not as reliable as url segments. I tend to use the latter more. For instance, for my process module's modal landing pages, I append some pre-determined url segments and check that instead. Below, some rough examples of both approaches (untested, mostly written from memory :-)).

Something along those lines...

I think I already tried to use url segments but in execute() method I'll get "404" errors. So URL segments doesn't seem to be fully supported in ProcessModules.

Link to comment
Share on other sites

1 hour ago, Gadgetto said:

I think I already tried to use url segments but in execute() method I'll get "404" errors. So URL segments doesn't seem to be fully supported in ProcessModules.

Ah, nope. They are fully supported. I use them all the time in most of my modules. Maybe show us some code?

  • Like 1
Link to comment
Share on other sites

22 hours ago, kongondo said:

Ah, nope. They are fully supported. I use them all the time in most of my modules. Maybe show us some code?

Here is the init() and ___execute() part of ProcessSnipWire:

(please have a look at the "Refresh" button down below - at the end of source code)

    /**
     * Initialize the module.
     * (Called before any execute functions)
     * 
     */
    public function init() {
        parent::init();
        
        // Get SnipWire module config.
        // (Holds merged data from DB and default config. 
        // This works because of using the ModuleConfig class)
        $this->snipwireConfig = $this->wire('modules')->get('SnipWire');

        // Get activated $currencies from SnipWire module config
        $this->currencies = $this->snipwireConfig->currencies;

        $this->snipWireRootUrl = rtrim($this->wire('pages')->get('snipwire')->url, '/') . '/';
        $this->currentUrl = rtrim($this->wire('input')->url, '/') . '/';
    }    

    /**
     * The SnipWire Dashboard page.
     *
     * @return page markup
     *
     */
    public function ___execute() {
        $modules = $this->wire('modules');
        $user = $this->wire('user');
        $config = $this->wire('config');
        $input = $this->wire('input');
        $sniprest = $this->wire('sniprest');
        
        $this->browserTitle($this->_('SnipWire Dashboard'));
        $this->headline($this->_('SnipWire Dashboard'));
        
        if (!$user->hasPermission('snipwire-dashboard')) {
            $this->error($this->_('You dont have permisson to use the SnipWire Dashboard - please contact your admin!'));
            return '';
        }
        
        $this->_includeAssets(
            self::assetsIncludeDaterangePicker | 
            self::assetsIncludeCurrencyPicker | 
            self::assetsIncludeApexCharts
        );

        $startDate = $this->_getStartDate();
        $endDate = $this->_getEndDate();
        $currency = $this->_getCurrency();
        $action = $this->_getInputAction();
        $forceRefresh = false;
        if ($action == 'refresh') {
            $this->message(SnipREST::getMessagesText('cache_refreshed'));
            $forceRefresh = true;
        } elseif ($action == 'reset') {
            $this->message($this->_('Store performance date range set to default.'));
            $this->_resetDateRange();
        }

        $packages = $sniprest->getDashboardData(
            "$startDate 00:00:00",
            "$endDate 23:59:59",
            $currency,
            SnipREST::cacheExpireDefault,
            $forceRefresh
        );
        $dashboard = $this->_prepareDashboardData($packages);
        unset($packages);

        if (!$dashboard) {
            $out =
            '<div class="dashboard-empty">' .
                $this->_('Dashboard data could not be fetched') .
            '</div>';
            return $this->_wrapDashboardOutput($out);
        }

        $out = $this->_buildDashboardFilter($startDate, $endDate, $currency);

        $out .= $this->_renderPerformanceBoxes(
            $dashboard[SnipRest::resourcePathDataPerformance],
            $currency
        );

        $chart = $this->_renderChart(
            $dashboard[SnipRest::resourcePathDataOrdersSales],
            $dashboard[SnipRest::resourcePathDataOrdersCount],
            $currency
        );

        /** @var InputfieldForm $wrapper */
        $wrapper = $modules->get('InputfieldForm');

            /** @var InputfieldMarkup $f */
            $f = $modules->get('InputfieldMarkup');
            $f->label = $this->_('Performance Chart');
            $f->icon = 'bar-chart';
            $f->value = $chart;
            $f->columnWidth = 100;
            $f->collapsed = Inputfield::collapsedNever;
            
        $wrapper->add($f);

        $out .= $wrapper->render();

        /** @var InputfieldForm $wrapper */
        $wrapper = $modules->get('InputfieldForm');

            /** @var InputfieldMarkup $f */
            $f = $modules->get('InputfieldMarkup');
            $f->label = $this->_('Top Customers');
            $f->icon = self::iconCustomer;
            $f->value = $this->_renderTableTopCustomers($dashboard[SnipRest::resourcePathCustomers]);
            $f->columnWidth = 50;
            $f->collapsed = Inputfield::collapsedNever;

        $wrapper->add($f);

            /** @var InputfieldMarkup $f */
            $f = $modules->get('InputfieldMarkup');
            $f->label = $this->_('Top Products');
            $f->icon = self::iconProduct;
            $f->value = $this->_renderTableTopProducts($dashboard[SnipRest::resourcePathProducts], $currency);
            $f->columnWidth = 50;
            $f->collapsed = Inputfield::collapsedNever;

        $wrapper->add($f);

        $out .= $wrapper->render();

        /** @var InputfieldForm $wrapper */
        $wrapper = $modules->get('InputfieldForm');

            /** @var InputfieldMarkup $f */
            $f = $modules->get('InputfieldMarkup');
            $f->label = $this->_('Recent Orders');
            $f->icon = self::iconOrder;
            $f->value = $this->_renderTableRecentOrders($dashboard[SnipRest::resourcePathOrders]);
            $f->columnWidth = 100;
            $f->collapsed = Inputfield::collapsedNever;
            
        $wrapper->add($f);

        $out .= $wrapper->render();

        /** @var InputfieldButton $btn */
        $btn = $modules->get('InputfieldButton');
        $btn->id = 'refresh-data';
        //$btn->href = $this->currentUrl . '?action=refresh';
        $btn->href = $this->currentUrl . 'refresh'; // <--- https://processwire.moduledev/pw/setup/snipwire/refresh
                                                    // and leads to "The process returned no content."
        $btn->value = $this->_('Refresh');
        $btn->icon = 'refresh';
        /*
        $btn->addActionLink(
            $this->currentUrl . '?action=refresh_all', 
            'Refresh Complete Snipcart Cache',
            'refresh'
        );
        */
        $btn->showInHeader();

        $out .= $btn->render();

        return $this->_wrapDashboardOutput($out);
    }

 

Link to comment
Share on other sites

On 8/10/2019 at 2:11 PM, dragan said:

Do you have an ___executeRefresh() method? There's plenty of infos in this old thread: 

 

Hi @draganI don't have an ___executeRefresh() method. And as I read in the old thread you posted, it strengthens my view that url segments are not ideal for my purpose.

  • Like 1
Link to comment
Share on other sites

On 8/10/2019 at 2:58 PM, bernhard said:

Can we see your executeRefresh() method? Maybe it's just a typo? I'd try "foo" + "executeFoo" instead of "refresh" - maybe it's a reserved word for whatever reason or conflicting somewhere else?

I didn't think I'd need to add executeRefresh(), executeReset(), executeThis(), executeThat(), ... methods. This would fragmentize the source of a module a lot. I thought it works like in frontend, where I can enable URL segments and then the parts of URL paths like /mymodule/this/that/ are simply assigned to urlSegement(1) = "this" ,urlSegement(2) = "that". And the request wouldn't be routed to /mymodule/this/that/ but /mymodule/.

From this point of view, I don't see any advantage for using url segments in process modules.

It could also be that I still don't understand how URL segments are working!? (which is probably the case)

Link to comment
Share on other sites

I've never used url segments in the admin myself. You can always use url parameters though. Only thing you have to keep in mind is that PW strips off all parameters except the ID parameter when a user is not logged in and wants to visit yoursite.com/yourbackend/yourmodule/?id=1&foo=2&bar=3 which would mean he would be redirected to yoursite.com/yourbackend/yourmodule/?id=1

Link to comment
Share on other sites

16 minutes ago, bernhard said:

I've never used url segments in the admin myself. You can always use url parameters though. Only thing you have to keep in mind is that PW strips off all parameters except the ID parameter when a user is not logged in and wants to visit yoursite.com/yourbackend/yourmodule/?id=1&foo=2&bar=3 which would mean he would be redirected to yoursite.com/yourbackend/yourmodule/?id=1

@kongondo initially suggested that I could also use URL segments and therefore the discussion. I'll stay with URL params which is OK in backend.

Link to comment
Share on other sites

On 8/11/2019 at 5:42 PM, Gadgetto said:

This would fragmentize the source of a module a lot. I thought it works like in frontend, where I can enable URL segments and then the parts of URL paths like /mymodule/this/that/ are simply assigned to urlSegement(1) = "this" ,urlSegement(2) = "that". And the request wouldn't be routed to /mymodule/this/that/ but /mymodule/.

From this point of view, I don't see any advantage for using url segments in process modules.

It could also be that I still don't understand how URL segments are working!? (which is probably the case)

@Gadgetto

My bad. I misled you a bit. I can't find it now, but @teppo made an excellent post about the executeWhatever() aspect of Process modules. In Process Modules, unlike URL segments in the frontend, ProcessWire will 'jealously guard' the first URL Segment, i.e. the Whatever part of execute....(). In other words, if your Process module has a first URL segment, it will look for a method in your Process module named executeYourFirstURLSegment(). If it doesn't find that, rather than render what is in execute(), it returns the error, Processwire: Unrecognized Path and the content The process returned no content. However, this only applies to the first URL Segment. After that, i.e. 2nd, 3rd, etc URL segments will resolve to whatever you decide based on the code you have in the method of the first URL Segment. For instance, in the case /admin/mymodule/firsturlsegment/whatever/, ProcessWire will not complain if there is no 'whatever' as long as firsturlsegment has content. Please find an example Process module below and the demo of it. The example is a bit rudimentary but you get the idea. Normally, I don't include the content of what I want the 2nd, etc URL segments to resolve to within the executeWhatever() method itself. I usually throw those in their own methods or even class. 

Example

In this example, executeColours() is our gateway to anything we want the 2nd URL segment to resolve to. The 'red', 'green', etc segments do not exist independently (i.e. no corresponding executeXXX() methods for them). ProcessWire does not complain since the first segment /colours/ exists as executeColours().

Spoiler

<?php namespace ProcessWire;

class ProcessDemoURLSegments extends Process implements Module {

    public static function getModuleInfo() {

		return array(
			'title' => 'Demo URL Segments',
			'author' => 'Kongondo',
			'version' => "1",
			'summary' => 'Process Module Demoing URL Segments.',
			'singular' => true,
			'autoload' => false,
		);

	}

    const PAGE_NAME = 'demourlsegments';

    public function __construct() {
        parent::__construct();
    }

    public function init() {
        parent::init();
    }

    public function execute() {
        $out = 'My Demo URL Segments Module';
        return $out;
    }

    public function executeColours() {

        $input = $this->wire('input');
        $sanitizer = $this->wire('sanitizer');
        $urlSeg2 = $sanitizer->pageName($input->urlSegment2);

        if($urlSeg2 == 'red') $colour = 'red';
        elseif($urlSeg2 == 'green') $colour = 'green';
        elseif($urlSeg2 == 'blue') $colour = 'blue';
        else $colour = 'main';

        $out = $this->menu($colour);
        $out .= "<h2 class='{$colour}'>Demo URL Segments Process Module.</h2>";


        return $out;
    }

    private function menu($currentMenuItem) {

        $menuItems = array(
			'main' => $this->_('Main'),
			'red' => $this->_('Red'),
			'green' => $this->_('Green'),
			'blue' => $this->_('Blue'),
		);

        $out = "<ul class='demo nav uk-navbar-nav pw-primary-nav'>";


        $seg1 = 'colours/';

		foreach ($menuItems as $key => $value) {
			// determine 'active' menu item
			$on = $key == $currentMenuItem ? 'menu_item on uk-active' : 'menu_item';
			$seg2 = $key;
			$href = $this->wire('page')->url . $seg1 . $seg2 . "/";
			$out .= "<li><a class='{$on}' href='{$href}'>{$value}</a></li>";
		}

		$out .= "</ul>";

		return $out;


    }


    public function ___install() {
        $page = new Page();
        $page->template = 'admin';
        $page->parent = $this->wire('pages')->get($this->wire('config')->adminRootPageID);
        $page->title = 'Demo URL Segments';
        $page->name = self::PAGE_NAME;
        $page->process = $this;
        $page->save();
    }

    public function ___uninstall() {}



}

 

Demo

demo-url-segments-process-module.thumb.gif.a5e42256e30d0331d1597bc5985537bf.gif

 

Edited by kongondo
  • 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...