My code:
// View/Activities/index.ctp
...
<div>
<?php echo $this->requestAction('/Activities/ajax_list/'.$categoryId,['return']);?>
</div>
...
//View/Activitest/ajax_list.ctp
....
<?php echo $this -> Html -> image("/img/add1.jpg"); ?>
...
<?php echo $this->Html->link('add_project', array('controller'=>'projects', 'action'=>'add', $categoryId)); ?>
....
I want to include the view 'ajax_list' into the 'index',and it has been displayed but the url of image and link was wrong.
Then I debug the Cake/Routing/RequestActionTrait.php , "requestAction" function I find "$request = new Request($params);" the $request->base , $request->webroot are null.
Could some one tell me how should I fix it?
The $base/$webroot properties not being set in the new request might be considered a bug, or maybe the docs are just missing a proper example solution, I can't tell for sure, you might want to report this over at GitHub and see what the devs say.
Use view cells instead of requestAction()!
Whenever applicable you're better off using view cells instead of requesting actions, as they avoid all the overhead that comes with dispatching a new request.
See Cookbook > Views > View Cells
No models involved? Use elements!
In case no models are involed, and all you are doing is generating HTML, then you could simply use elements.
See Cookbook > Views > Elements
Fixing requestAction()
A possible workaround would be to use a dispatcher filter that fills the empty $base/$webroot properties with the necessary values, something like
src/Routing/Filter/RequestFilterFix.php
namespace App\Routing\Filter;
use Cake\Event\Event;
use Cake\Routing\DispatcherFilter;
class RequestFixFilter extends DispatcherFilter
{
public function beforeDispatch(Event $event)
{
$request = $event->data['request'];
/* #var $request \Cake\Network\Request */
if ($request->param('requested')) {
$request->base = '/pro';
$request->webroot = '/pro/';
$request->here = $request->base . $request->here;
}
}
}
config/bootstrap.php
// ...
// Load the filter before any other filters.
// Must at least be loaded before the `Routing` filter.
DispatcherFactory::add('RequestFix');
DispatcherFactory::add('Asset');
DispatcherFactory::add('Routing');
DispatcherFactory::add('ControllerFactory');
// ...
See also Cookbook > Routing > Dispatcher Filters > Building a Filter
Related
my index controller this and showing good html and header and footer is working correct but when i want to add method the css and html not working .
public function index()
{
$data['clients_list'] = $this->clients_model->get_all_clients();
$this->load->view('template/header');
$this->load->view('clients/index', $data);
$this->load->view('template/footer');
}
this is my add method where i want to add html as header and footer
public function add()
{
$this->load->view('template/header');
$this->load->view('clients/add');
$this->load->view('template/footer');
}
The way you are using $this->load->view() is not supported in the framework. You should only be loading one view. If you wish to include multiple views within a single view you must save them within the data to be rendered in the master view and echo them out within that view. To do this you use the third parameter of the view function explained at the codeigniter api: Very bottom of page
An example of this would be:
Controller:
function index(){
$data['clients_list'] = $this->clients_model->get_all_clients();
$data['header'] = $this->load->view('template/header', $data, TRUE);
$data['footer'] = $this->load->view('template/footer', $data, TRUE);
$this->load->view('clients/index', $data);
}
View:
<?php echo $header; ?>
<!-- YOUR INDEX PAGE CONTENT-->
<?php echo $footer; ?>
The third parameter of view() tells the framework to pre-render the view and output the contents as a string value which allows you to save as a variable and echo into the primary page.
Phil Sturgeon wrote a wonderful template library that I have been using in my projects that allows for a webforms style "master page" that you can have the rest of your views rendered inside of so that you do not have to build your header/footer view each time and inject it into every view.
Phil Sturgeon Template Library
Suppose, I have 3 stores.
I want to disable a module in Store 2. I only want it to be enabled in Store 1 and Store 3.
I see that I can do it by:-
Going to System -> Configuration -> Advanced
Selecting desired store from Current Configuration Scope dropdown list.
But this does not work fully.
And, I also don't want to check store in the module code itself or create system configuration field for the module to check/uncheck store to enable/disable.
What I am expecting is by adding some code in app/etc/modules/MyNamespace_MyModule.xml. Can we do it this way?
To disable a module on the store scope, I've found it's possible to do it like this:
Move app/code/core/Mage/Core/Model/Config.php to app/code/local/Mage/Core/Model/Config.php
Inside Config.php find the method "loadModulesConfiguration" Don't change anything, but add the following code to make the method look like this.
public function loadModulesConfiguration($fileName, $mergeToObject = null, $mergeModel=null)
{
$disableLocalModules = !$this->_canUseLocalModules();
if ($mergeToObject === null) {
$mergeToObject = clone $this->_prototype;
$mergeToObject->loadString('<config/>');
}
if ($mergeModel === null) {
$mergeModel = clone $this->_prototype;
}
$modules = $this->getNode('modules')->children();
foreach ($modules as $modName=>$module) {
if ($module->is('active')) {
// Begin additional code
if((bool)$module->restricted) {
$restricted = explode(',', (string)$module->restricted);
$runCode = (isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : 'default');
if(in_array($runCode, $restricted)) {
continue;
}
}
// End additional code
if ($disableLocalModules && ('local' === (string)$module->codePool)) {
continue;
}
if (!is_array($fileName)) {
$fileName = array($fileName);
}
foreach ($fileName as $configFile) {
$configFile = $this->getModuleDir('etc', $modName).DS.$configFile;
if ($mergeModel->loadFile($configFile)) {
$mergeToObject->extend($mergeModel, true);
}
}
}
}
return $mergeToObject;
}
The new code will cause the method to also check for a new node in the module xml file, <restricted>. If the node exists, the value would be a comma separated list of store codes that you do NOT want the module to load on. If you have multiple stores, the $_SERVER variable "MAGE_RUN_CODE" should be set with the current store code. If it's not set, the script will fallback to assuming the store code is "default" which is what it is by default unless for some bizarre reason you decide to change that in the backend.
A modules xml file could then look like this:
<?xml version="1.0"?>
<config>
<modules>
<MyPackage_MyModule>
<active>false</active>
<restricted>mystore1,mystore4,mystore5</restricted>
<codePool>local</codePool>
</MyPackage_MyModule>
</modules>
</config>
With this, the module will not even load while on the stores with a store code of mystore1, mystore4, or mystore5. The <restricted> tag is entirely optional, if you omit it the module will load as it normally would.
This configuration just disables module output in layout for frontend, but module controllers, event observers, admin pages, etc still working.
Also don't forget to specify your module name in layout files definition, otherwise all the layout file content will be loaded for a particular store:
<config>
<layout>
<module_alias module="Module_Name">
<file>yourlayoutfile.xml</file>
</module_alias>
</layout>
</config>
If you are developing a module and want to disable full its functionality on the frontent for a particular store, then you should create a configuration field of "Yes/No" type and check its value via Mage::getStoreConfigFlag('config/field/path') in your module code.
I was using Eric solution for a while. In my case I disabled certain module responsible for Layered Navigation in one of my shops - thus returning to default Layered Navigation behaviour.
And it looked like its working, but after a while I've noticed that layered navigation options stopped to appear where they should. Soon I've noticed that in fact the module that should not work on this shop continued to work. Then I realized that when I disable configuration cache Eric's solution works, but after enabling it again it stops.
After a while I realized it had to work that way, with configuration cache enabled, because Eric's solution includes (or not) specified config files in global xml only while this xml is being generated. Then its cached and called from cache only. So when it was generated from site which should use some module it was included, and then used also on site which wasn't suppose to use it.
Anyway I worked out another solution, based on Eric's code (using restricted in modules config). I thought Magento should decide what to load when class is being requested. Then it could check what is current MAGE_RUN_CODE and use it dynamically.
There is a method in Mage_Core_Model_Config which is responsible for getting class name: getGroupedClassName.
Here is the code I used there:
if (strpos($className, 'Pneumatig_') !== false) {
$var = substr($className, 0, strpos($className, '_', strpos($className, '_') + 1));
if (isset($this->_xml->modules->$var)) {
if ((bool)$this->_xml->modules->$var->restricted === true) {
$code = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : 'default';
if (strpos((string)$this->_xml->modules->$var->restricted, $code) !== false) {
$className = '';
}
}
}
}
This Pneumatig condition is because all my modules start from Company name, so i wanted to avoid not necessary processing, but its optional, code should work without it, or you can change it to anything else.
Then I get actual module name [Company]_[Module], and then check if its enabled in _xml (which is current configuration object). If it is restricted I clear $className so it force Magento to load the default in next line.
And this code is added just before is empty condition:
// Second - if entity is not rewritten then use class prefix to form class name
if (empty($className)) {
if (!empty($config)) {
$className = $config->getClassName();
}
if (empty($className)) {
$className = 'mage_'.$group.'_'.$groupType;
}
if (!empty($class)) {
$className .= '_'.$class;
}
$className = uc_words($className);
}
$this->_classNameCache[$groupRootNode][$group][$class] = $className;
return $className;
And for your convenience i paste whole getGroupedClassName code:
public function getGroupedClassName($groupType, $classId, $groupRootNode=null)
{
if (empty($groupRootNode)) {
$groupRootNode = 'global/'.$groupType.'s';
}
$classArr = explode('/', trim($classId));
$group = $classArr[0];
$class = !empty($classArr[1]) ? $classArr[1] : null;
if (isset($this->_classNameCache[$groupRootNode][$group][$class])) {
return $this->_classNameCache[$groupRootNode][$group][$class];
}
$config = $this->_xml->global->{$groupType.'s'}->{$group};
// First - check maybe the entity class was rewritten
$className = null;
if (isset($config->rewrite->$class)) {
$className = (string)$config->rewrite->$class;
} else {
/**
* Backwards compatibility for pre-MMDB extensions.
* In MMDB release resource nodes <..._mysql4> were renamed to <..._resource>. So <deprecatedNode> is left
* to keep name of previously used nodes, that still may be used by non-updated extensions.
*/
if (isset($config->deprecatedNode)) {
$deprecatedNode = $config->deprecatedNode;
$configOld = $this->_xml->global->{$groupType.'s'}->$deprecatedNode;
if (isset($configOld->rewrite->$class)) {
$className = (string) $configOld->rewrite->$class;
}
}
}
//START CHECKING IF CLASS MODULE IS ENABLED
if (strpos($className, 'Pneumatig_') !== false) {
$var = substr($className, 0, strpos($className, '_', strpos($className, '_') + 1));
if (isset($this->_xml->modules->$var)) {
if ((bool)$this->_xml->modules->$var->restricted === true) {
$code = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : 'default';
if (strpos((string)$this->_xml->modules->$var->restricted, $code) !== false) {
$className = '';
}
}
}
}
//END CHECKING IF CLASS MODULE IS ENABLED
// Second - if entity is not rewritten then use class prefix to form class name
if (empty($className)) {
if (!empty($config)) {
$className = $config->getClassName();
}
if (empty($className)) {
$className = 'mage_'.$group.'_'.$groupType;
}
if (!empty($class)) {
$className .= '_'.$class;
}
$className = uc_words($className);
}
$this->_classNameCache[$groupRootNode][$group][$class] = $className;
return $className;
}
My clients install of Magento 1.8.1.0 has a problematic module that breaks another site's menu on a multi-store setup. The solution above posted by Eric Hainer didn't work for this install, so I altered it slightly:
Instead of using $_SERVER['MAGE_RUN_CODE'], I used $_SERVER['SERVER_NAME']. Worked like a charm. :)
So instead of:
$runCode = (isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : 'default');
use:
$runCode = (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'www.site1.com');
and instead of:
<restricted>mystore1,mystore4,mystore5</restricted>
use:
<restricted>www.site2.com,www.site3.com</restricted>
obviously changing "www.site1.com", "www.site2.com", and "www.site3.com" with your own locations.
Thanks for the idea Eric :)
Also interesting solution ,
http://inchoo.net/ecommerce/magento/how-to-activatedeactivate-magento-module-per-a-website-level/
I have specified a frontend_model in system.xml for an entry field. I did this because I wanted to make a field read-only. There may have been a more straightforward way to achieve that, but that's where I am at the moment. The thing is I cannot get the field to display the data it should.
I have a button that when pressed, populates the read-only field. That works fine. But when I hit 'Save Config', the data disappears from the field. The reason it disappears is because I can't find out what I should set the field's value to. Below tries using the getEscapedValue() method of Varien_Data_Form_Element_Abstract, but it returns nothing. And as usual with Magento, there is no documentation to speak of.
class Mypackage_MyModule_Block_Adminhtml_System_Config_DisabledText extends Mage_Adminhtml_Block_System_Config_Form_Field
{
protected function _prepareLayout()
{
parent::_prepareLayout();
if (!$this->getTemplate()) {
$this->setTemplate('mypackage/system/config/disabled_text.phtml');
}
return $this;
}
public function render(Varien_Data_Form_Element_Abstract $element)
{
$element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
return parent::render($element);
}
protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
$originalData = $element->getOriginalData();
$this->addData(array(
'my_value' => $element->getEscapedValue(),
'html_id' => $element->getHtmlId(),
));
return $this->_toHtml();
}
}
disabled_text.phtml contains the following:
<input id="<?php echo $this->getHtmlId() ?>" value="<?php echo $this->getMyValue(); ?>" class=" input-text" type="text" disabled/>
Thanks.
This is one of those places where you need to look at how Magento itself is doing something similar to what you want to do. If you look at the Mage_Adminhtml_Block_System_Config_Form_Field class's _getElementHtml
protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
return $element->getElementHtml();
}
you can see that this method accepts a form element that's already been instantiated (based on what's in system.xml), and then this element renders itself with getElementHtml. That means when Magento needs to render (and, in turn, get the value) it does so in from the element object. Some crude debugging will let us know where getElementHtml can be located
protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
var_dump(get_class($element));
return $element->getElementHtml();
}
Something like Varien_Data_Form_Element_Text will be dumped to the screen. In turn, this class inherits form Varien_Data_Form_Element_Abstract, which contains the following definition
public function getElementHtml()
{
$html = '<input id="'.$this->getHtmlId().'" name="'.$this->getName()
.'" value="'.$this->getEscapedValue().'" '.$this->serialize($this->getHtmlAttributes()).'/>'."\n";
$html.= $this->getAfterElementHtml();
return $html;
}
So, when Magento wants to get the value for a system config field, it uses the above PHP code to render the input. So, if you want to do the same in your template, I'd try something like this
Up in the class, assign a block property with the entire element. This is actually more efficient that plucking values out of the elements, since all PHP needs to store is an object reference.
protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
$this->setMyElement($element);
return $this->_toHtml();
}
Then, in the template, copy the code from magento's rendering, replacing the "$this" keyword with your saved element
<?php $_element = $this->getMyElement(); ?>
<!-- check the quoting/escaping on this html/php, I didn't actually run it, but the concept is sound -->
<input disabled="disabled" id="<?php echo $_element->getHtmlId();?>" name="<?php echo $_element->getName();?>"
value="<?php echo $_element->getEscapedValue();?>"
<?php echo $_element->serialize($_element->getHtmlAttributes());?>
/>
<?php echo $_element->getAfterElementHtml(); ?>
When you're working with Magento, try to think like a Magento developer. Instead of "I need to figure out how to make it do X", think "I need to add this feature to the store in the same way the rest of my teammates have". Then look how the core team did it, and copy their implementation, changing as little as you need to.
It does get easier the more you work with the system!
Complete beginner here. I want to create a new tab on each page that has a custom action. When clicked, it takes you to a new page which has custom HTML on it along with the text or the original article.
So far I could create a new Tab and could give a custom action mycustomaction to it. I am pasting what I did so far here. Please let me know if I am using the correct hooks etc. and what is a better way to achieve this basic functionality.
So far with their docs I have done this:
#Hook for Tab
$wgHooks['SkinTemplateContentActions'][] = 'myTab';
#Callback
function myTab( $content_actions) {
global $wgTitle;
$content_actions['0'] = array(
'text' => 'my custom label',
'href' => $wgTitle->getFullURL( 'action=mycustomaction' ),
);
return true;
}
#new action hook
$wgHooks['UnknownAction'][] = 'mycustomaction';
#callback
function mycustomaction($action, $article) {
echo $action;
return true;
}
This gives me error:
No such action
The action specified by the URL is invalid. You might have mistyped the URL, or followed an incorrect link. This might also indicate a bug in the software used by yourplugin
What I was doing wrong:
$content_actions[‘0’] should simply be $content_actions[] (minor nitpick)
$content_actions is passed-by-reference, it should be function myTab( &$content_actions ) {}
mycustomaction() should do something along the lines of
if ( $action == ‘mycustomaction’ ) {
do stuff; return false;
}
else {
return true;
}
It should use $wgOut->addHTML() instead of echo
Thanks a lot everyone for your help!
I want to get the last query CakePHP ran. I can't turn debug on in core.php and I can't run the code locally. I need a way to get the last sql query and log it to the error log without effecting the live site. This query is failing but is being run.
something like this would be great:
$this->log($this->ModelName->lastQuery);
Thanks in advance.
For Cake 2.0, the query log is protected so this will work
function getLastQuery() {
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
Tested in CakePHP v2.3.2
$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);
In CakePHP 1.x, the data you want is accessible in DataSource::_queriesLog. Cake doesn't really provide a getter method for this member, but the underlying language being PHP, nothing stops you from doing the following:
In app/app_model.php:
function getLastQuery()
{
$dbo = $this->getDatasource();
$logs = $dbo->_queriesLog;
return end($logs);
}
You can use this inline.
$dbo = $this->Model->getDatasource();
// store old state
$oldStateFullDebug = $dbo->fullDebug;
// turn fullDebug on
$dbo->fullDebug = true;
// Your code here! eg.
$this->Model->find('all');
// write to logfile
// use print_r with second argument to return a dump of the array
Debugger::log(print_r($dbo->_queriesLog, true));
// restore fullDebug
$dbo->fullDebug = $oldStateFullDebug;
Simple you can use showLog() function
var_dump($this->YourModel->getDataSource()->showLog());
This is a very late answer, i know, but for whoever needs this in the future, you can always restrict setting debug to your IP, For example:
Configure::write('debug', 0);
if($_SERVER["REMOTE_ADDR"] == '192.168.0.100'){
Configure::write('debug', 2); //Enables debugging only for your IP.
}
Combination of Matt's and blavia's solution (works when debug is not 2):
$dbo = $this->Model->getDatasource();
$oldStateFullDebug = $dbo->fullDebug;
$dbo->fullDebug = true;
// find or whatever...
$this->Model->find("all");
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
CakeLog::write("DBLog", $lastLog['query']);
$dbo->fullDebug = $oldStateFullDebug;
Having a quick skim of the book, cakephp api getLog you could turn on logTransaction. Although having not used it, I'm not sure how it will perform.
Otherwise you could experiment with FirePHP and here is the a guide for it,
You might try DebugKit, although off the top of my head I think you do still need debug 2 to get it to work.
Hopefully something might give you a lead. :)
You can use this:
$log = $this->Model->getDataSource()->getLog(false, false);
pr($log);die;
There are two methods to view the query in CakePHP.
Both methods you have to add the below one line in app/Config/core.php
Configure::write('debug', 2);
First methods :
debug($this->getLastQuery());
where you want to get the query add above line and call this function getLastQuery() on same controller using below code
public function getLastQuery() {
$dbo = $this->TModel->getDatasource(); //Here TModel is a model.what table you want to print
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
second method :
add the below line in the any Elements files.
<?php echo $this->element('sql_dump'); ?>
This will help you.
echo '<pre>';
$log = $this->YOUR_MODEL->getDataSource();
print_r($log);
exit;