joomla: extend publish method through the controller - joomla2.5

I think my approach may be off, but this seems like a common need, so i'm hoping i'm not too far off. Any input is appreciated. When the 'publish/unpublish' button is clicked, i'd like to read 'getTask()' and take my own actions, after the core's 'publish' method completes. Here's where I start:
In the controller, in my own 'publish' method i call parent::publish. So far no problem. Then I want to read getTask and pass it to the model function.
CONTROLLER_CLASS extends jCONTROLLER_ADMIN
public function publish()
{
parent::publish();
$model = $this->getModel();
$myPublish = $this->getTask();
$model->modelVariable = $myPublish;
//or
$model->doCustomPublishWork();
}

This seemed to work out pretty well.
public function publish()
{
$publishAffliate = $this->getTask();
$cid = JRequest::getVar('cid');//affiliates DB record ID.
$fileName = "C:\wamp\bin\apache\apache2.4.2\conf\affilatesTest.txt";
$fHandle = fopen($fileName, 'a');
switch($publishAffliate)
{
case 'publish':
fwrite($fHandle, "\npublished site ID = ". $cid[0]);
break;
case 'unpublish':
fwrite($fHandle, "\nunpublished site ID = ". $cid[0]);
break;
}
parent::publish();
}

Related

How to fill state/region/subregion selections when page is opened in edit mode?

In Laravel 8/livewire 2/aplinejs I need to fill state/region/subregion, which are tables in db
and I select subregion from priorly selected regions and select regions from priorly selected, like
public function updatedSelectedState($state_id)
{
$this->regionsSelectionArray = Region::getRegionsSelectionArray($state_id, 'A');
$this->detailsForm['state_id'] = $state_id;
}
public function updatedSelectedRegion($region_id)
{
$this->subregionsSelectionArray = Subregion::getSubregionsSelectionByRegionIdArray($region_id);
$this->selectedSubregion = null;
}
it works ok for data inserting , but when I open editor in “edit” mode and I neeed to fill initvalue I
failed how do it. I remember when I made similar tasks with jquery I have common bool var which I set to true
when jquery was inited. And in onChange event I checked this var .
But how can I do it in livewire ?
Thanks in advance!
Call the below functions in your edit method
Example:
public function updatedSelectedState($state_id)
{
$this->changeSelectedState($state_id);
}
public function updatedSelectedRegion($region_id)
{
$this->changeSelectedRegion($region_id);
}
public function changeSelectedState($state_id){
$this->regionsSelectionArray = Region::getRegionsSelectionArray($state_id, 'A');
$this->detailsForm['state_id'] = $state_id;
}
public function changeSelectedRegion($region_id)
{
$this->subregionsSelectionArray = Subregion::getSubregionsSelectionByRegionIdArray($region_id);
$this->selectedSubregion = null;
}
public function edit(){
// $state_id = provide your state id here
// $region_id = provide your region id here
$this->changeSelectedState($state_id);
$this->changeSelectedRegion($region_id);
}

Testing network which uses AFNetworking with OCMock

I have a class Network that contain next method:
- (void)fetchRecords {
Network * __weak weakSelf = self;
[self.sessionManager POST:#"" parameters:#{#"parameter":"param1"}
success:^(NSURLSessionDataTask *task, id responseObject) {
[weakSelf setRecordsWithLists:responseObject];
}
failure:nil];
}
Property sessionManager is AFHTTPSessionManager class.
I want to test my network communication. I want to check that if success block executed then invoked setRecordsWithLists: method.
I use OCMock, I googled and write next test code:
- (void)tesNetworkSuccessExecuteSetRecords {
id partiallyMockedSessionManager = [OCMockObject partialMockForObject:self.network.sessionManager];
[[partiallyMockedSessionManager expect] POST:OCMOCK_ANY parameters:OCMOCK_ANY success:OCMOCK_ANY failure:OCMOCK_ANY];
[[[partiallyMockedSessionManager expect] andDo:^(NSInvocation *invocation) {
void (^successBlock)(NSURLSessionDataTask *task, id responseObject);
[invocation getArgument:&successBlock atIndex:4];
successBlock(nil, #[#"first", #"second"]);
}] POST:OCMOCK_ANY parameters:OCMOCK_ANY success:OCMOCK_ANY failure:OCMOCK_ANY];
self.network.sessionManager = partiallyMockedAuthorizationSessionManager;
[self.network fetchRecords];
}
Please, tell how to return my own response for success block, if do it wrong. And how to verify that setRecordsWithLists: called from success block.
Well, you are actually setting the expectation twice, which would mean you are expecting the method to be called twice too. If that is not what you intend, you should delete the first expectation.
On the other hand, since you need to check if your method is called, you probably want to create a partial mock for your self.network object. With the partial mock (or spy), you can set the expectation for your method, with any argument you prefer, and verify it to complete the test.
Your code finally should look like this:
- (void)tesNetworkSuccessExecuteSetRecords {
id partiallyMockedSessionManager = [OCMockObject partialMockForObject:self.network.sessionManager];
[[[partiallyMockedSessionManager expect] andDo:^(NSInvocation *invocation) {
void (^successBlock)(NSURLSessionDataTask *task, id responseObject);
[invocation getArgument:&successBlock atIndex:4];
successBlock(nil, #[#"first", #"second"]);
}] POST:OCMOCK_ANY parameters:OCMOCK_ANY success:OCMOCK_ANY failure:OCMOCK_ANY];
id spyNetwork = OCMPartialMock(self.network);
[[spy expect] setRecordsWithLists:OCMOCK_ANY];
self.network.sessionManager = partiallyMockedAuthorizationSessionManager;
[self.network fetchRecords];
[spyNetwork verify];
}
Again, you may add the argument of your preference in the expectation. Beware of the name of the method, it should begin with 'test', otherwise it may not be run or recognized as a test by XCode.

Magento: Get product id in php block for available in list.phtml

I'm trying to get an attribute for it to be listed on list.phtml, the form that is being made is as follows:
I created a module on the Block and created a function which captures the attribute:
protected function getPreOrder()
{
$productId = $this->getRequest()->getParam('id');
$product = Mage::getModel('catalog/product')->load($productId);
$preOrder = $product->getNewsFromDate();
$preOrder = substr($preOrder, 0, 10);
return $preOrder;
}
public function getViewList()
{
if(strtotime(date('Y-m-d')) <= strtotime($this->getPreOrder()))
{
return true;
} else {
return false;
}
}
However, nothing is returned. I also did this same method to view.phtml and it worked perfectly. That goes for a file before the function getChildHtml() phtml, is not being edited list.phtml
That makes sense to create a loop, but the loop is already list.phtml!
What would be the way?
I thank you.
Have you debugged your block function to see if the product id is correct and if its loading the model correctly ??
Also debug the template list.phtml to check if its correctly loading the block type ?
get_class($this);
and see what class type is it.

How do I insert test data in Play Framework 2.0 (Scala)?

I'm having some problems with making my tests insert fake data in my database. I've tried a few approaches, without luck. It seems that Global.onStart is not run when running tests within a FakeApplication, although I think I read that it should work.
object TestGlobal extends GlobalSettings {
val config = Map("global" -> "controllers.TestGlobal")
override def onStart(app: play.api.Application) = {
// load the data ...
}
}
And in my test code:
private def fakeApp = FakeApplication(additionalConfiguration = (
inMemoryDatabase().toSeq +
TestGlobal.config.toSeq
).toMap, additionalPlugins = Seq("plugin.InsertTestDataPlugin"))
Then I use running(fakeApp) within each test.
The plugin.InsertTestDataPlugin was another attempt, but it didn't work without defining the plugin in conf/play.plugins -- and that is not wanted, as I only want this code in the test scope.
Should any of these work? Have anyone succeeded with similar options?
Global.onStart should be executed ONCE (and only once) when the application is launched, whatever mode (dev, prod, test) it is in. Try to follow the wiki on how to use Global.
In that method then you can check the DB status and populate. For example in Test if you use an in-memory db it should be empty so do something akin to:
if(User.findAll.isEmpty) { //code taken from Play 2.0 samples
Seq(
User("guillaume#sample.com", "Guillaume Bort", "secret"),
User("maxime#sample.com", "Maxime Dantec", "secret"),
User("sadek#sample.com", "Sadek Drobi", "secret"),
User("erwan#sample.com", "Erwan Loisant", "secret")
).foreach(User.create)
}
I chose to solve this in another way:
I made a fixture like this:
def runWithTestDatabase[T](block: => T) {
val fakeApp = FakeApplication(additionalConfiguration = inMemoryDatabase())
running(fakeApp) {
ProjectRepositoryFake.insertTestDataIfEmpty()
block
}
}
And then, instead of running(FakeApplication()){ /* ... */}, I do this:
class StuffTest extends FunSpec with ShouldMatchers with CommonFixtures {
describe("Stuff") {
it("should be found in the database") {
runWithTestDatabase { // <--- *The interesting part of this example*
findStuff("bar").size must be(1);
}
}
}
}

Duplicate DB sessions created upon Zend_Auth login

I must be doing something wrong. I can't seem to find the answer to my problem anywhere on the Web, and this generally means that the solution is so simple that no one needs an answer on it.
I am using a database to store my session. I set it up in my bootstrap like this:
protected function _initDBSessions(){
$resource = $this->getPluginResource('db'); //from config.ini?
$db = $resource->getOptions();
$adapter = new Zend_Db_Adapter_Pdo_Mysql($db["params"]);
Zend_Db_Table_Abstract::setDefaultAdapter($adapter);
$config = array('name'=>'sessions','primary'=>'id','modifiedColumn'=>'modified','dataColumn'=>'data','lifetimeColumn'=>'lifetime');
$options = array(
"strict"=>FALSE,
"name"=>"eCubed",
"use_cookies"=>FALSE
);
Zend_Session::setOptions($options);
Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_DbTable($config));
}
Next in my bootstrap is my plugin setup
protected function _initPlugins(){
Zend_Controller_Front::getInstance()->registerPlugin(new Acl_Acl());
}
My Acl_Acl looks like this:
class Acl_Acl extends Zend_Controller_Plugin_Abstract{
public function preDispatch(Zend_controller_request_abstract $request){
$acl = new Zend_Acl();
//add roles
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$GUEST));
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$BASIC),Acl_Levels::$GUEST);
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$SHOP),Acl_Levels::$BASIC);
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$OFFICE),Acl_Levels::$SHOP);
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$EXECUTIVE),Acl_Levels::$OFFICE);
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$OWNER));
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$ADMIN),Acl_Levels::$OWNER);
//add resources
$acl->addResource("index");
$acl->addResource("authenticate");
$acl->addResource("error");
$acl->addResource("employees");
$acl->addResource("mold");
$acl->addResource("search");
$acl->addResource("shop");
$acl->addResource("user");
//access rules
$acl->allow(null,array('index','error','authenticate')); //default resources
//Guest member access
$acl->allow(Acl_Levels::$GUEST,'mold',array('index','list-molds'));
$acl->allow(Acl_Levels::$GUEST,'user',array('index','login','new-profile','my-profile'));
//SHOP Member Access
$acl->allow(Acl_Levels::$BASIC,'mold',array('get-mold','get-part','get-order','get-orders','get-parts','print-mold-labels','print-part-labels'));
$acl->allow(Acl_Levels::$BASIC,'user',array('my-profile','profile'));
//OFFICE Member Access
//EXECUTIVE Member Access
//OWNER Member Access
//ADMIN Member Access
//current user
if(Zend_Auth::getInstance()->hasIdentity()){
$level = Zend_Auth::getInstance()->getIdentity()->level;
} else {
$level = Acl_Levels::$GUEST;
}
$conroller = $request->controller;
$action = $request->action;
try {
if(!$acl->isAllowed($level,$conroller,$action)){
$request->setControllerName('application-error');
$request->setActionName('not-authorized');
}
} catch (Exception $e){
$request->setControllerName("application-error");
$request->setActionName("error");
$error = new Zend_Controller_Plugin_ErrorHandler();
$error->type = Zend_Controller_Plugin_ErrorHandler::EXCEPTION_OTHER;
$error->request = clone($request);
$error->exception = $e;
$request->setParam('error_handler',$error);
}
}
}
My Authentication Controller has the following action:
public function loginAction(){
$this->_helper->viewRenderer->setNoRender(TRUE);
$loginForm = new Form_Login();
$form = $loginForm->getLoginForm();
$form->setAction("/authenticate/login");
if($this->getRequest()->isPost()){
if($form->isValid($_POST)){
$email = $form->getValue('email');
$pass = $form->getValue('password');
$authAdapter = $this->getAuthAdapter();
$authAdapter ->setIdentity($email)
->setCredential($pass);
$result = Zend_Auth::getInstance()->authenticate($authAdapter);
if($result->isValid()){
$omit = array('password','timestamp','temp_password','active','created');
$identity = $authAdapter->getResultRowObject(NULL,$omit);
$authStorage = Zend_Auth::getInstance()->getStorage();
$authStorage->write($identity);
$nickname = $identity->nickname ? $identity->nickname : $identity->first_name;
$this->_helper->flashMessenger("Welcome back $nickname");
//Zend_Debug::dump($identity); exit;
$this->_redirect("/");
} else {
$this->_helper->flashMessenger("Unable to log you in. Please try again");
$this->_redirect("/");
}
}
}
}
My Database Structure:
id : int
modified: int
lifetime: int
data: text
All is well, right? Well, no...
First of all, a session is created every time someone who is not logged in refreshes or navigates to a page. This is acceptable, I guess...
The problem I have is that when I do finally log in, I can see that the database is storing the Zend_Auth identity and Flashmessenger perfectly, BUT ...
... IT IS ALSO CREATING A PHANTOM ROW IN THE DATABASE AS IF A NON-LOGGED IN USER IS NAVIGATING THE WEBSITE....
This makes authentication impossible because when the user is redirected the "Profile" page, for example, Zend is looking at the phantom session data which contains absolutely no data!
Below is the information stored in the Zend_Session database table as proof that stuff is stored:
Zend_Auth|a:1:{s:7:"storage";O:8:"stdClass":7:{s:2:"id";s:1:"2";s:5:"email";s:17:"wes#****.com";s:10:"first_name";s:6:"Wesley";s:9:"last_name";s:7:"*";s:5:"level";s:5:"basic";s:8:"nickname";s:3:"Wes";s:9:"lastlogin";s:19:"2011-07-14 19:30:36";}}__ZF|a:1:{s:14:"FlashMessenger";a:1:{s:4:"ENNH";i:1;}}FlashMessenger|a:1:{s:7:"default";a:1:{i:0;s:16:"Welcome back Wes";}}
This has been driving me nuts for 2 days now. I am under the impression that Zend_Session automatically uses only 1 session to store data, but these multiple entries are driving me mad!!
I hope I've given someone enough information to work off of.
I figured out this problem...
As expected, the solution was a simple typo...
I don't know how to dramatically write the answer here, but the problem was...
My Database table, called "sessions" had the wrong data type.
The datatype for the id column was set to "int" (11)
instead it should be set to "char" (32)
DUH! I hope the 4 days I spent on this problem helps someone else out!