Set default value for static method in bootstrap - zend-framework

this paragraph is part of 'Zend Framework In Action' book.
SearchIndexer::setIndexDirectory(ROOT_DIR . '/var/search_index');
Places_Db_Table_Row_Observable::attachObserver('SearchIndexer');
As you can see, it’s simply a case of setting the directory to store the search index files
and attaching the class to the list of observers in Places_Db_Table_Row_Observable
using the name of the class.
Now I have a problem! I put this code in bootstrap file in runapp method, but it can't recognize the directory that I set in bootstrap!
It shows me this error
An error occurred exception 'Zend_Search_Exception' with message 'No index directory specified' in E:\xampp\php\PEAR\Zend\Search\Lucene.php:497
=======================================================
other type of my question :
I have this code in bootstrap file (runApp method):
SearchIndexer::setIndexDirectory(ROOT_DIR.'/var/search_index');
Places_Db_Table_Row_Observable::attachObserver('SearchIndexer');
I set search directory path in SearchIndexer class, but there is a prob!
When I use of below code in controller action, it can't recognize the directory that I set in bootstrap!
controller code :
$index = Places_Search_Lucene::open(SearchIndexer::getIndexDirectory());
this is seachIndexer code :
public static function setIndexDirectory($directory){
if(!is_dir($directory)) {
throw new Exception('Directory for SearchIndexer is invalid ('. $directory .')');
}
self::$_indexDirectory = $directory;
}
public static function getIndexDirectory(){
return self::$_indexDirectory;
}

Your getIndexDirectory function does not return a path so Places_Search_Lucene::open fails.
Maybe setIndexDirectory fails to set the path. Do some debugging on that.
Maybe you use the class in your bootstrap before it gets loaded by zend autoloader. Where do you perform this?
Try to load the class manually before usage:
Zend_Loader::loadClass('Path_To_SearchIndexer',
array(
'/home/production/mylib',
)
);
Documentation on zend loader: http://framework.zend.com/manual/en/zend.loader.load.html

Related

NetSuite SuiteScript - Constants And Inclusion

I have a NetSuite SuiteScript file (2.0) in which I want to include a small library of utilities I've built. I can do that fine, and access the functions in the included library. But I can't access the constants I've defined in that library - I have to re-declare them in the main file.
Here's the main file:
define(['N/record', 'N/search', './utils.js'],
function (record, search, utils) {
function pageInit(scriptContext) {
isUserAdmin = isCurrentUserAdmin(contextRecord);
if (isUserAdmin) {
alert('Administrator Role ID is ' + ADMINISTRATOR_ROLE);
// Do something for Admin users
}
return;
}
return {
pageInit: pageInit
};
});
You can see I include the file ./utils.js in it. Here's utils.js:
const ADMINISTRATOR_ROLE = 11;
function isCurrentUserAdmin(currentRecord) {
return ADMINISTRATOR_ROLE == nlapiGetRole();
}
That's the entire file - nothing else.
In the main file, the call to the function isCurrentUserAdmin works fine. It correctly tells me whether the current user is an admin. Note that I don't have to preface the call to isCurrentUserAdmin with utils. (utils.isCurrentUserAdmin doesn't work - it gives me the error JS_EXCEPTION TypeError utils is undefined). But when the code gets to the line that uses ADMINSTRATOR_ROLE, I get the error JS_EXCEPTION ReferenceError ADMINISTRATOR_ROLE is not defined. BTW, if I put the constant definition of ADMINISTRATOR_ROLE in the main file instead of utils.js, I get the same error when utils.js tries to use it. The only way I can get it to work is if I have the line defining the constant in both files.
Why does the inclusion work for the function, but not the constant? Am I including the library wrongly? I thought I'd have to use it as utils.isCurrentUserAdmin rather than just isCurrentUserAdmin, but to my surprise that's not the case, as I say above.
If you have utils.js like below, you can use utils.ADMINISTRATOR_ROLE and utils.isCurrentUserAdmin() in your main file.
/**
*#NApiVersion 2.0
*/
define ([],
function() {
const ADMINISTRATOR_ROLE = 11;
function isCurrentUserAdmin() {
// check here
}
return {
ADMINISTRATOR_ROLE: ADMINISTRATOR_ROLE,
isCurrentUserAdmin: isCurrentUserAdmin
};
});
Try
define(['N/record', 'N/search', 'SuiteScripts/utils']
You need to make sure any member you need to access in another module needs to be exported in the source module using the return statement

how to use the hook processUpload_postProcessAction in my extension?

Can anyone here know how to use the processUpload_postProcessAction hook in my extension?
I have created a hook folder and added a php file named class.tx_lms_tcemain.php
I have added the following lines in my extension's ext_localconf.php
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUploadClass'][] = 'EXT:wr_dw_lms/hooks/class.tx_lms_tcemain.php:tx_lms_tcemain';
In the PHP file inside hooks folder contains following code:
<?php
class tx_lms_tcemain {
function processUpload_postProcessAction (&$filename, t3lib_TCEmain
$parentObject) {
$this->addFlashMessage(
'Blog created successfully!',
'Status',
\TYPO3\CMS\Core\Messaging\AbstractMessage::OK,TRUE
);
}
}
?>
This one does not work. My code is not getting executed. Can anyone here help me?
Try to write this in your ext_localconf.php
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_extfilefunc.php']['processData'][] = 'Vendor\WrDwLms\Hooks\Tcemain\';
Try to change your code in ext_localconf.php to
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'][] = 'EXT:wr_dw_lms/hooks/class.tx_lms_tcemain.php:tx_lms_tcemain';
Note the "processUpload" instead of the "processUploadClass".
I'd recommend however you use proper namespacing:
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUploadClass'][] =
'Vendor\WrDwLms\Hooks\Tcemain';
Your Hook could look like this (put it in wr_dw_lms/Classes/Hooks/):
namespace Vendor\WrDwLms\Hooks;
use TYPO3\CMS\Core\DataHandling\DataHandler
class Tcemain {
public function processUpload_postProcessAction(&$filename, DataHandler $parentObject) {
....
}
}
Edit: as for the code you edited into your question ($this->addFlashMessage()) that of course cannot work if you do not implement the method in your class.

Yii RBAC make Users update profile by himself

I'm trying to do this with mongodbauthmanager. I'm follow step by step in Usage section but finally i'm getting PHP warning: Illegal offset type. I had posted this question at Yii Extension before clone to SO:
Please tell me what is wrong?
1// Config
'authManager'=>array(
'class' =>'CMongoDbAuthManager',
'showErrors' => true,
),
2// Create auth items in db
$auth = new CMongoDbAuthManager();
$bizRule = 'return Yii::app()->user->id==$params["User"]->_id;';
$auth->createTask('updateSelf', 'update own information', $bizRule);
//I had tried with $auth->createOperation() but they has the same error
$role = $auth->createRole('user');
$role->addChild('updateSelf');
$auth->save();
and here is result in db
result in db http://i.minus.com/iIpXoBlDxaEfo.png
**3// Checking access in controller ** - UPDATE CODE AND ERROR
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$params = array('User'=>$model);
if (!Yii::app()->user->checkAccess('updateSelf', Yii::app()->user->id,$params) )
{
throw new CHttpException(403, 'You are not authorized to perform this action');
}
//another statement ...
}
4// Getting error:
Fatal error : Cannot use object of type MongoId as array in F:\Data\03. Lab\www\yii\framework\web\auth\CAuthManager.php(150) : eval()'d code on line 1
RESOLVED PROBLEM
Base-on the answer of #Willem Renzema, I resolve my problem. Now, I update here and hope it useful for someone have this error.
0// First, config authManager with defaultRoles
'authManager'=>array(
'class'=>'CMongoDbAuthManager',
'showErrors' => true,
'defaultRoles'=> array('user'),//important, this line help we don't need assign role for every user manually
),
1// Fix save id in UserIdentity class
class UserIdentity extends CUserIdentity
{
private $_id;
//...
public function authenticate()
{
//...
$this->_id = (string)$user->_id;//force $this save _id by string, not MongoId object
//...
}
//...
}
2// Fix $bizrule in authe items
($bizrule will run by eval() in checkAccess)
//use _id as string, not MongoId object
$bizRule = 'return Yii::app()->user->id==(string)$params["User"]->_id;';
3// And user checkAccess to authorization
public function actionUpdate($id){
/**
* #var User $model
*/
$model=$this->loadModel($id);
$params = array('User'=>$model);
if (!Yii::app()->user->checkAccess('updateSelf', $params) )
{
throw new CHttpException(403, 'You are not authorized to perform this action');
}
//...
}
4// Done, now we can use checkAccess :D
First off, your original use of checkAccess was correct. Using Yii::app()->user->checkAccess() you are using the following definition:
http://www.yiiframework.com/doc/api/1.1/CWebUser#checkAccess-detail
Now, CWebUser's implementation of checkAccess calls CPHPAuthManager's implementation, which is where you encountered your problem with an illegal offset type.
http://www.yiiframework.com/doc/api/1.1/CPhpAuthManager#checkAccess-detail
An Illegal offset type means you are attempting to access an array element by specifying its key (also known as: offset) with a value that doesn't work as a key. This could be another array, an object, null, or possibly something else.
Your stack trace posted on the extensions page reveals that the following line gives the problem:
if(isset($this->_assignments[$userId][$itemName]))
So we have two possibilities for the illegal offset: $userId and $itemName.
Since $itemName is clearly a string, the problem must be with $userId.
(As a side note, the fact that your stack trace revealed surrounding code of this error also revealed that, at least for CPHPAuthManager, you are using a version of Yii that is prior to 1.1.11. Observe that lines 73 and 74 of https://github.com/yiisoft/yii/blob/1.1.11/framework/web/auth/CPhpAuthManager.php do not exist in your file's code.)
At this point I would have guessed that the problem is that the specified user is not logged in, and so Yii::app()->user->id is returning null. However, the new error you encountered when placing Yii::app()->user->id as the 2nd parameter of checkAccess reveals something else.
Since the 2nd parameter is in fact what should be the $params array that appears in your bizRule. Based on the error message, this means that Yii::app()->user->id is returning a mondoId type object.
I was unfamiliar with this type of object, so looked it up:
http://php.net/manual/en/class.mongoid.php
Long story short, you need to force Yii::app()->user->id to return the string value equivalent of this mondoId object. This likely set in your UserIdentity class in the components folder. To force it to be a string, simply place (string) to force a type conversion.
Example:
$this->_id = (string)$User->_id;
Your exact code will vary, based on what is in your UserIdentity class.
Then, restore your checkAccess to the signature you had before, and it should eliminate the Illegal offset error you encountered originally.
Note however that I have not used this extension, and while performing the following actions should fix this issue, it may cause new issues if the extension relies on the fact that Yii::app()->user->id is a mondoId object, and not a string.

change script path calling view action helper

I want to create different view scripts for each modules in my application. My structure look like that:
-- application
-- modules
-- default
-- views
-- default
-- scripts
-- fluid
--scripts
I set default script path in Zend Controller Plugin, which preDispatch() is executed with the request:
$view->setScriptPath(sprintf('%s/modules/%s/views/%s/scripts', APPLICATION_PATH, $module, $views));
Everything works great until i call action from view:
$this->action('activity-stream', 'index', 'observation');
Application throws an exception with message:
script 'index/activity-stream.phtml' not found in path (C:/wamp/www/erp/application/modules/observation/views\scripts/;C:\wamp\www\erp\application/modules/user/views/fluid/scripts/)
Looks like, when calling module with View Action Helper, script path is not set properly. Any idea how to achieve that?
Problem not solved, but i dit what i want in a different way. Each controller within any module of my application inherits my custom action controller that inherits Zend_Controller_Action. Inside that custom controller i have something like this:
public function init() {
parent::init();
$module = $this->_request->getModuleName();
$config = new Zend_Config_Ini(APPLICATION_PATH . "/configs/modules.ini", $module);
$layout = isset($config->layout) ? $config->layout : 'default';
$views = isset($config->views) ? $config->views : 'default';
$this->view->layout()->setLayout($layout);
$this->view->setScriptPath(sprintf('%s/modules/%s/views/%s/scripts', APPLICATION_PATH, $module, $views));
}
It's not exactly what i wanted, but solves my problem.

How to use Zend Framework's Partial Loop with Objects

I am quite confused how to use partialLoop
Currently I use
foreach ($childrenTodos as $childTodo) {
echo $this->partial('todos/_row.phtml', array('todo' => $childTodo));
}
$childrenTodos is a Doctrine\ORM\PersistantCollection, $childTodo is a Application\Models\Todo
I tried doing
echo $this->partialLoop('todos/_row.phtml', $childrenTodos)
->setObjectKey('Application\Models\Todo');
But in the partial when I try to access properties/functions of my Todo class, I cant seem to get them always ending up with either call to undefined method Zend_View::myFunction() when I use $this->myFunction() in the partial or if I try $this->todo->getName() I get "Call to a member function getName() on a non-object". How do I use partialLoops?
Try this
echo $this->partialLoop('todos/_row.phtml', $childrenTodos)
->setObjectKey('object');
Then in your partial you can access the object like this
$this->object
object is the name of the variable that an object will be assigned to
You can also do this once in your Bootstrap or other initialization class if you have access to the view object like so
protected function initPartialLoopObject()
{
$this->_view->partialLoop()->setObjectKey('object');
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
$viewRenderer->setView($this->_view);
}
I also had "Call to function on non object" error when trying suggested syntax, seems like they've changed something on later versions of Zend Framework. The following works for me on ZF1.12:
echo $this->partialLoop()
->setObjectKey('object')
->partialLoop('todos/_row.phtml', $childrenTodos);