Joomla 3.x Get Module Parameters Within Ajax Call - php

I am playing around with a custom build module in Joomla 3.x that uses Ajax to display some real-time data. Within the function executed by the Ajax call I need to access the module parameters and I'm not sure how to do this. Normally, I could just put $var = $params('paramName', 'default') in the module PHP file to get the param but this is not available when the call is made by Ajax. This is my template code that executes the Ajax call:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery.get('index.php?option=com_ajax&module=whatsinport&method=getWhatsInPort&format=json', function(data) {
console.log(data);
var response = jQuery.parseJSON(data);
This is the code in my helper.php class:
class modWhatsInPortHelper {
public static function getWhatsInPortAjax()
{
$results = array();
$results['status'] = 'ok';
$app = JFactory::getApplication();
$serverName = $app->getCfg('mod_whatsinport_serverName');
$dbName = $app->getCfg('mod_whatsinport_dbName');
$dbUser = $app->getCfg('mod_whatsinport_dbUser');
$dbPwd = $app->getCfg('mod_whatsinport_dbPwd');
$connectionInfo = array( "Database"=>$dbName, "UID"=>$dbUser, "PWD"=>$dbPwd, "ReturnDatesAsStrings"=>true);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
The $app->getCfg does not appear to do what I want - I am guessing it is only used for Joomla config settings. I also tried:
$app = JFactory::getApplication();
$params = $app->getParams();
$serverName = $params->get('mod_whatsinport_serverName');
$dbName = $params->get('mod_whatsinport_dbName');
$dbUser = $params->get('mod_whatsinport_dbUser');
$dbPwd = $params->get('mod_whatsinport_dbPwd');
But this didn't work either. I forgot to include my module config file:
<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="3.1.0" client="site" method="upgrade">
<name>WhatsInPort</name>
<author>Chris Krohn</author>
<version>1.0.0</version>
<description>Displays a list of current vessels in port.</description>
<files>
<filename>mod_whatsinport.xml</filename>
<filename module="mod_whatsinport">mod_whatsinport.php</filename>
<filename>index.html</filename>
<filename>helper.php</filename>
<filename>tmpl/default.php</filename>
<filename>tmpl/index.html</filename>
</files>
<config>
<fields name="params">
<fieldset name="basic">
<field name="mod_whatsinport_serverName" type="text" default="" label="Server Name" description="NETBIOS name of the database server to connect to." />
<field name="mod_whatsinport_dbName" type="text" default="" label="Database Name" description="Name of the database with the HMLOG table." />
<field name="mod_whatsinport_dbUser" type="text" default="" label="Database User" description="User name to login to the server with." />
<field name="mod_whatsinport_dbPwd" type="password" default="" label="Database Password" description="Password to login to the server with." />
</fieldset>
</fields>
</config>
</extension>

Figured it out. Should be:
$app = JFactory::getApplication();
$module = JModuleHelper::getModule('mod_whatsinport','WhatsInPort');
$params = new JRegistry($module->params);
$serverName = $params->get('mod_whatsinport_serverName');
$dbName = $params->get('mod_whatsinport_dbName');
$dbUser = $params->get('mod_whatsinport_dbUser');
$dbPwd = $params->get('mod_whatsinport_dbPwd');

Retrieve data of a parameter within the getjax() method.
public static function getAjax(){
$app = JFactory::getApplication();
$module = JModuleHelper::getModule('my_module');
$params = new JRegistry($module->params);
return $params ->get('myparams');
}

Related

Magento 2 - Controller returning blank page

Been spending the last 1 day to find a fix for this.
Basically everything works normal if I delete all the contents of generated folder and then generate the files dynamically by accessing the pages rather than doing setup:di:compile.
On the production though, I'm forced to do setup:di:compile and I end up with this certain admin module page being empty.
This is the controller of the page:
namespace Eadesigndev\AWB\Controller\Adminhtml\Index;
use Eadesigndev\Awb\Api\AwbRepositoryInterface;
use Eadesigndev\Awb\Model\Awb;
use Eadesigndev\Awb\Model\AwbFactory;
use Eadesigndev\Awb\Helper\Data as DataHelper;
use Magento\Framework\Registry;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\Session;
use Magento\Framework\View\Result\PageFactory;
use Magento\Backend\App\Action;
class Edit extends Action
{
/**
* Authorization level of a basic admin session
*
*
*/
const ADMIN_RESOURCE = 'Eadesigndev_Awb::awb';
protected $resultPageFactory;
private $awbRepository;
private $awbFactory;
private $registry;
private $session;
private $dataHelper;
private $awbModel;
public function __construct(
Context $context,
PageFactory $resultPageFactory,
AwbRepositoryInterface $awbRepository,
AwbFactory $awbFactory,
Awb $awbModel,
Registry $registry,
DataHelper $dataHelper
) {
$this->resultPageFactory = $resultPageFactory;
$this->awbRepository = $awbRepository;
$this->awbFactory = $awbFactory;
$this->registry = $registry;
$this->awbModel = $awbModel;
$this->session = $context->getSession();
$this->dataHelper = $dataHelper;
parent::__construct($context);
}
/**
* Edit action new awb.
*
* #return \Magento\Backend\Model\View\Result\Page
*/
public function execute()
{
$id = $this->getRequest()->getParam('entity_id');
if ($id) {
$model = $this->awbRepository->getById($id);
if (!$model->getEntityId()) {
$this->messageManager->addErrorMessage(__('This field no longer exists.'));
/** \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultFactory->create();
return $resultRedirect->setPath('*/*/');
}
} else {
echo '3';
$model = $this->awbFactory->create();
}
/** #var Session $data */
$data = $this->session->getFormData(true);
if (!empty($data)) {
$model->setData($data);
}
$this->registry->register('awb_data', $model);
echo 'wat';
/** #var \Magento\Backend\Model\View\Result\Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$resultPage->addBreadcrumb(__('Edit new Awb'), __('Edit new Awb'));
$resultPage->getConfig()->getTitle()->prepend(__('Edit new Awb'));
echo 'pac';
return $resultPage;
}
the controller currently returns a blank page with my debug strings:
3watpac
in /vendor/eadesignro/awb/Block/Adminhtml/Xtea I have the next files:
Edit (folder)
Edit.php
EditAwb.php
in /vendor/eadesignro/awb/view/adminhtml/layout I have the next files:
shipping_awb_index_edit.xml
shipping_awb_index_editawb.xml
shipping_awb_index_index.xml
Content of shipping_awb_index_edit.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<update handle="editor"/>
<head></head>
<body>
<referenceContainer name="content">
<block class="Eadesigndev\Awb\Block\Adminhtml\Xtea\Edit" name="awb_edit"/>
</referenceContainer>
<referenceContainer name="left">
<block class="Eadesigndev\Awb\Block\Adminhtml\Xtea\Edit\Tabs" name="awb_edit_tabs">
<block class="Eadesigndev\Awb\Block\Adminhtml\Xtea\Edit\Tab\General" name="awb_edit_tab_general"/>
<action method="addTab">
<argument name="name" xsi:type="string">general_section</argument>
<argument name="block" xsi:type="string">awb_edit_tab_general</argument>
</action>
<block class="Eadesigndev\Awb\Block\Adminhtml\Xtea\Edit\Tab\Curier" name="awb_edit_tab_curier"/>
<action method="addTab">
<argument name="name" xsi:type="string">curier_section</argument>
<argument name="block" xsi:type="string">awb_edit_tab_curier</argument>
</action>
</block>
</referenceContainer>
</body>
</page>
This is the page:
magento_admin_secreturl/shipping_awb/index/edit/key/xxxxxx
these are the routers:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="shipping_awb" frontName="shipping_awb">
<module name="Eadesigndev_Awb" before="Magento_Backend"/>
</route>
<route id="edit_awb" frontName="edit_awb">
<module name="Eadesigndev_Awb" before="Magento_Backend"/>
</route>
</router>
</config>
Any possible idea on why $this->resultPageFactory->create(); is simply returning nothing on production but working on development?
The index page works both on production and dev without any problem.
I can provide more info if needed, thank you!
The problem was a CAPSLOCK mistake in the namespace.
namespace Eadesigndev\AWB\Controller\Adminhtml\Index;
should have been
namespace Eadesigndev\Awb\Controller\Adminhtml\Index;
notice the 'AWB' becoming 'Awb'.
Apparently in development mode, the namespaces are not case-sensitive? or perhaps they are all transformed to capslock. If anyone has a clue, leave a comment, thanks!
For anyone who is still getting a blank page in Admin Controller, but the alternative solutions (case-sensitive) doesn't work for you, you may try running php bin/magento setup:di:compile.
This helped me.

Getting backend model in system.xml from config path in Magento 2

I am trying to get backend model class name from system.xml
Right now i am using this code.
magento/app/code/Company/Sso/etc/adminhtml/system.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<section id="admin">
<group id="sso_saml" translate="label" sortOrder="100" showInDefault="1" showInWebsite="0" showInStore="0" >
<label>Single Sign on(SAML)</label>
<field id="is_enabled" translate="label comment" type="select" sortOrder="0" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Is Enabled SAML</label>
<comment>Enable Single Sign On</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
</group>
</section>
</system>
Magento Code
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$structure = $objectManager->create('Magento\Config\Model\Config\StructureFactory');
$field = $objectManager->create('Magento\Config\Model\Config\Structure')->getElementByConfigPath('admin/sso_saml/is_enabled');
print json_encode($field->getData());
Output:
{"id":"is_enabled","path":"admin/sso_saml","_elementType":"field"}
But i need source_model, can anyone help?
You need to be in the adminhtml area in order to load the rest of the data:
e.g
<?php
require __DIR__ . '/app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$appState = $objectManager->get('Magento\Framework\App\State');
$appState->setAreaCode('adminhtml');
$field = $objectManager->create('Magento\Config\Model\Config\Structure')->getElementByConfigPath('customer/create_account/auto_group_assign');
echo $field->getData()['source_model'];
> Magento\Config\Model\Config\Source\Yesno
You could potentially use \Magento\Framework\App\State::emulateAreaCode to fetch the data from within a non-admin context if necessary.
Here is full solution after implementing Matt's solution.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$appState = $objectManager->get('Magento\Framework\App\State');
$field = $appState->emulateAreaCode('adminhtml', function($path){
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$appState = $objectManager->get('Magento\Framework\App\State');
$appState->setAreaCode('adminhtml');
$field = $objectManager->create('Magento\Config\Model\Config\Structure')
->getElementByConfigPath($path->getPath());
return $field;
}, [$path]);
$value = $path->getData()['backend_model'];

Joomla Component: View: Get values from field

I'm new to Joomla, especially to component development. Anyway, here's my question:
site\views\plaingallery\tmpl\default.xml
<?xml version="1.0" encoding="utf-8"?>
<metadata>
<layout title="COM_PLAINGALLERY_PLAINGALLERY_VIEW_DEFAULT_TITLE">
<message>
<![CDATA[COM_PLAINGALLERY_PLAINGALLERY_VIEW_DEFAULT_DESC]]>
</message>
</layout>
<fields name="request"
addfieldpath="/administrator/components/com_plaingallery/models/fields">
<fieldset name="request">
<field name="galleryFolder" type="folderlist" default="" recursive="true"
label="Select a folder" directory="images" filter="" exclude="" width="300"
hide_none="true" hide_default="true" stripext="" />
</fieldset>
</fields>
</metadata>
site\views\plaingallery\view.html.php
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla view library
jimport('joomla.application.component.view');
/**
* HTML View class for the PlainGallery Component
*/
class PlainGalleryViewPlainGallery extends JViewLegacy
{
// Overwriting JView display method
function display($tpl = null)
{
// Assign data to the view
$this->msg = 'I am new to Joomla';
// Display the view
parent::display($tpl);
}
}
My question is: How do I access the value from the field[name="galleryFolder"] the user provided in the menu configuration?
Thanks for your help! I really do appreciate it.
This parameter is located in the query variable of the menu item.
You can try this for example:
$app = JFactory::getApplication();
/* Default Page fallback*/
$active = $app->getMenu()->getActive();
if (NULL == $active) {
$active = $app->getMenu()->getDefault();
}
if ( isset($active->query['galleryFolder']) ) {
$galleryFolder = $active->query['galleryFolder'];
}

onSave method for Editor Plugin in Joomla 3.6

I try to create a plugin which will display some text after creation of article in the editor.
/editors/materialwords/materialwords.xml:
<?xml version="1.0" encoding="utf-8"?>
<extension version="3.1" type="plugin" group="editors">
<name>Editor Material Words Count Plugin</name>
<creationDate>December 2016</creationDate>
<author>Aleksandr Lapenko</author>
<authorEmail>lapenkoak#gmail.com</authorEmail>
<authorUrl>vk.com/web_rider</authorUrl>
<copyright>Copyright</copyright>
<license>GNU General Public License version 2 or later; see LICENSE.txt</license>
<version>1.0.0</version>
<description>Calculate articles words count</description>
<files>
<filename plugin="materialwords">materialwords.php</filename>
</files>
<config>
<fields name="params">
<fieldset name="basic">
<field name="displayCount" type="text"
label="Display Count"
description="Words display count"
required="true"
size="10"
class="inputbox" />
</fieldset>
</fields>
</config>
</extension>
/editors/materialwords/materialwords.php:
<?php
defined('_JEXEC') or die;
class PlgEditorMaterialwords extends JPlugin
{
public function onSave($id)
{
return 'alert("' . $id . '");';
}
}
I install plugin and enable it. But something wrong (nothing when I save article in editor).
Please, help.
Best regards, Aleksandr.
if you want a plugin before save or after save event
onExtensionBeforeSave
onExtensionAfterSave
Actually editors plugins are type of editors that you can use in joomla back office, if you go in system - configuration in back office, for default editor you'll can choose your plugin because it is an editors plugin.
If you want to perform some action after save an article you'll have to write a content plugin with method onContentAfterSave(). This method takes 3 arguments :
$context, in your case it should be com_content.article, so test it before soing anything else
$article, the instance of the article you are saving
$isNew, a boolean, true if it is a new article, false if it is an udpate
Plugin code
class PlgContentMaterialwords extends JPlugin {
public function onContentAfterSave($context, $article, $isNew){
if ($context != 'com_content.content'){
return true;
}
// do stuff
}
}
Plugin declaration
<?xml version="1.0" encoding="utf-8"?>
<extension version="3.1" type="plugin" group="content">
<name>Editor Material Words Count Plugin</name>
<creationDate>December 2016</creationDate>
<author>Aleksandr Lapenko</author>
<authorEmail>lapenkoak#gmail.com</authorEmail>
<authorUrl>vk.com/web_rider</authorUrl>
<copyright>Copyright</copyright>
<license>GNU General Public License version 2 or later; see LICENSE.txt</license>
<version>1.0.0</version>
<description>Calculate articles words count</description>
<files>
<filename plugin="materialwords">materialwords.php</filename>
</files>
<config>
<fields name="params">
<fieldset name="basic">
<field name="displayCount" type="text"
label="Display Count"
description="Words display count"
required="true"
size="10"
class="inputbox" />
</fieldset>
</fields>
</config>
</extension>
Plugin to override save in javascript
With previous method you can not add javascript in this page. If you want to do such you have to add a onBeforeRender method. When clicking on an admin button, javascript method Joomla.submitbutton is called, so you can override it (take care of saving it before so you can call it after your process).
class PlgContentMaterialwords extends JPlugin
{
public function onBeforeRender()
{
if ( JFactory::getApplication()->isAdmin() ){
$document = JFactory::getDocument();
$document->addScriptDeclaration('
var Myvar = {};
Myvar.submitbutton = Joomla.submitbutton;
Joomla.submitbutton = function(task) {
if ( task == "article.save" || task == "article.apply" || task == "article.save2new" ){
alert("foo");
}
Myvar.submitbutton(task);
}
');
}
}
}

how to log different clients separately using log4php

I am new to log4php and I am trying to implement this on my custom framework. I have managed to get all db queries to file. what I want to do now is log it in a way so i can identify each client so that I can view debug my browser without seeing all the other clients in the same file.
xml
<configuration xmlns="http://logging.apache.org/log4php/">
<appender name="default" class="LoggerAppenderConsole" />
<appender name="default" class="LoggerAppenderFile">
<layout class="LoggerLayoutSimple" />
<param name="file" value="/var/SP/oiadm/docroot/cache/my.log" />
<param name="append" value="true" />
</appender>
<root>
<level value="debug" />
<appender_ref ref="default" />
</root>
</configuration>
php db class
if (defined ( 'OI_ENV' ) && OI_ENV == 'DEVELOPMENT') {
$debugtoolbar = array (
"stacktrace" => $stacktrace,
"sql" => $debug_sql,
"start" => $debug_sql_start,
"end" => $debug_sql_end
);
/*
if ( isset($_SESSION ['OI_DEBUG'] ['debugtoolbar'] ['database']) && count ( $_SESSION ['OI_DEBUG'] ['debugtoolbar'] ['database'] ) > 9) {
$_SESSION ['OI_DEBUG'] ['debugtoolbar'] ['database'] = null;
}
$_SESSION ['OI_DEBUG'] ['debugtoolbar'] ['database'] [] = $debugtoolbar;
*/
$log = $_SESSION['OI_DEBUG']['log'];
if(empty($log)){
// Create the logger
// Include and configure log4php
\Logger::configure(BASE_DIR . 'config.xml');
// The __CLASS__ constant holds the class name, in our case "Foo".
// Therefore this creates a logger named "Foo" (which we configured in the config file)
$log = \Logger::getLogger(__CLASS__);
}
$log->debug(json_encode($debugtoolbar));
}
UPDATE
I am using session id now, but this only works if user is logged in
if($_COOKIE['PHPSESSID']){
$log = $_SESSION['OI_DEBUG']['log'];
if(empty($log)){
// Create the logger
// Include and configure log4php
\Logger::configure(BASE_DIR . 'config.xml');
// The __CLASS__ constant holds the class name, in our case "Foo".
// Therefore this creates a logger named "Foo" (which we configured in the config file)
$log = \Logger::getLogger(__CLASS__);
}
$appender = new \LoggerAppenderRollingFile("default");
$appender->setFile(BASE_DIR . "cache/log4php_".$_COOKIE['PHPSESSID'].".log", true);
$appender->activateOptions();
$log->removeAllAppenders();
$log->addAppender($appender);
$log->debug(json_encode($debugtoolbar));
}

Categories