How to run same lines in all controllers init() function? - zend-framework

I need same 2 lines in all my controllers, each controller have its own init logic, but these two lines are common for all of them.
public function init()
{
$fm =$this->_helper->getHelper('FlashMessenger');
$this->view->messages = $fm->getMessages();
}
How can I avoid repeat code ?
Update:
Ok, the FlashMessenger was only an example, let's say I need write a log line in every action except for 'someAction' # 'someController'. So the new common lines should be.
$this->logger = new Zend_Log();
$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH.'/../logs/log.txt');
$this->logger->addWriter($writer);
$this->logger->log('Some Message',Zend_Log::DEBUG);
The question is, where should I place these lines in order to avoid repeat them in all init() of each controller.
These lines should be placed at bootstrap?. If so: How can skip log lines for 'someAction'.
Or should I implement a 'BaseController' and make all my controller extend from it. If so: How can I Autoload it? (Fatal error: Class 'BaseController' not found) .

Just subclass the controller:
class Application_ControllerAction extends Zend_Controller_Action {
public function init()
{
$fm =$this->_helper->getHelper('FlashMessenger');
$this->view->messages = $fm->getMessages();
}
}
class IndexController extends Application_ControllerAction {
}
You may also achieve the same writing Controller Plugin.
Edit:
Front controller plugins are executed on each request, just like the Controllers and have the same hook methods:
routeStartup(): prior to routing the request
routeShutdown(): after routing the request
dispatchLoopStartup(): prior to entering the dispatch loop
preDispatch(): prior to dispatching an individual action
postDispatch(): after dispatching an individual action
dispatchLoopShutdown(): after completing the dispatch loop
I addition, you may check controller params to execute the code only on selected requests:
if ('admin' == $this->getRequest()->getModuleName()
&& 'update' == $this->getRequest()->getActionName() ) …

You can access your flash messages through (you dont need to send anything from your controller to your view, it's all automated)
$fm = new Zend_Controller_Action_Helper_FlashMessenger();
Zend_Debug::dump($fm->getMessages());
in you view, i would also recommand that you encapsulate this code in a view helper like it is shown on this site http://grummfy.be/blog/191

In your bootstrap:
protected function _initMyActionHelpers() {
$fm = new My_Controller_Action_Helper_FlashMessenger();
Zend_Controller_Action_HelperBroker::addHelper($fm);;
}

How can I avoid repeat code ?
Write your own custom controller, implement that in init method of that controller, and then extend all controllers in your app from your custom controller.
But approach with separate view helper as #Jeff mentioned (look at link) is often taken as a better solution.
In your controller do only:
$this->_helper->flashMessanger('My message');
and view helper will do the rest.

It's not the reason for creating new custom controller. Just add this line to all you init() methods.
$this->view->messages = $this->_helper->getHelper('FlashMessenger')->getMessages();

Related

Get newly created id of a record before redirecting page

I would like to retrieve the id of a newly created record using javascript when I click on save button and just before redirecting page.
Do you have any idea please ?
Thank you !
One way to do this in Sugar 7 would be by overriding the CreateView.
Here an example of a CustomCreateView that outputs the new id in an alert-message after a new Account was successfully created, but before Sugar gets to react to the created record.
custom/modules/Accounts/clients/base/views/create/create.js:
({
extendsFrom: 'CreateView',
// This initialize function override does nothing except log to console,
// so that you can see that your custom view has been loaded.
// You can remove this function entirely. Sugar will default to CreateView's initialize then.
initialize: function(options) {
this._super('initialize', [options]);
console.log('Custom create view initialized.');
},
// saveModel is the function used to save the new record, let's override it.
// Parameters 'success' and 'error' are functions/callbacks.
// (based on clients/base/views/create/create.js)
saveModel: function(success, error) {
// Let's inject our own code into the success callback.
var custom_success = function() {
// Execute our custom code and forward all callback arguments, in case you want to use them.
this.customCodeOnCreate(arguments)
// Execute the original callback (which will show the message and redirect etc.)
success(arguments);
};
// Make sure that the "this" variable will be set to _this_ view when our custom function is called via callback.
custom_success = _.bind(custom_success , this);
// Let's call the original saveModel with our custom callback.
this._super('saveModel', [custom_success, error]);
},
// our custom code
customCodeOnCreate: function() {
console.log('customCodeOnCreate() called with these arguments:', arguments);
// Retrieve the id of the model.
var new_id = this.model.get('id');
// do something with id
if (!_.isEmpty(new_id)) {
alert('new id: ' + new_id);
}
}
})
I tested this with the Accounts module of Sugar 7.7.2.1, but it should be possible to implement this for all other sidecar modules within Sugar.
However, this will not work for modules in backward-compatibility mode (those with #bwc in their URL).
Note: If the module in question already has its own Base<ModuleName>CreateView, you probably should extend from <ModuleName>CreateView (no Base) instead of from the default CreateView.
Be aware that this code has a small chance of breaking during Sugar upgrades, e.g. if the default CreateView code receives changes in the saveModel function definition.
Also, if you want to do some further reading on extending views, there is an SugarCRM dev blog post about this topic: https://developer.sugarcrm.com/2014/05/28/extending-view-javascript-in-sugarcrm-7/
I resolved this by using logic hook (after save), for your information, I am using Sugar 6.5 no matter the version of suitecrm.
Thank you !

How to use a helper

I am creating a module that allows a user to input details into a form and save their details to allow relevant information to be forwarded to them at specified times.
To retrieve the details from the form and add them to the database I followed a tutorial and produced this code
public function saveAction()
{
$title = $this->getRequest()->getPost('title');
$f_name = $this->getRequest()->getPost('f_name');
$l_name = $this->getRequest()->getPost('l_name');
if ( isset($title) && ($title != '') && isset($f_name) && ($f_name != '') && isset($l_name) && ($l_name != '') ) {
$contact = Mage::getModel('prefcentre/prefcentre');
$contact->setData('title', $title);
$contact->setData('f_name', $f_name);
$contact->setData('l_name', $l_name);
$contact->save();
$this->_redirect('prefcentre/index/emailPreferences');
} else {
$this->_redirect('prefcentre/index/signUp');
}
}
The tutorial says to put it into the controller in a saveAction, and that works fine. However from my very limited understanding it would go in to a helper and i'd call the helper from the controller
I placed the above code in my helper and called it from within the saveAction using the following
Mage::helper('module/helpername');//returned blank screen and did not save
I also tried
Mage::helper('module/helpername_function');//returned error
My config has
<helpers>
<prefcentre>
<class>Ps_Prefcentre_Helper</class>
</prefcentre>
</helpers>
1 . Should this code go in a helper, if not where should it go?
2 . How do I call the helper(or the location the code need to go) to utilise the code?
1 . Should this code go in a helper, if not where should it go?
The actual code you posted imo is predestinated to be used within a controller action because it realizes a very specific process flow: Get user data for a specific case -> save if applicable -> redirect.
Secondly, a helper imo never should control route dispatching. It's a helper, not a controller.
I fail to see any use case where putting the method into a helper would give any advantages.
2 . How do I call the helper(or the location the code need to go) to
utilise the code?
Your definition uses <prefcentre> as alias, so if you did setup the helper the Magento standard way and using the file app/code/local/Ps/Prefcentre/Helper/Data.php, than your helper methods are callable like this:
Mage::helper('prefcentre')->myMethodName();

PHPUnit and Zend: Testing a function on a controller?

I have a controller called "SiteController". On it there is a normal indexAction which displays the frontpage. It's fairly easy to test this, but how would I test another function that is NOT an action with parameters. Let's say I have a function called "sendMail($to, $message)". How do I test that?
<?php
class ControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
public function testShowCallsServiceFind()
{
$this->dispatch('/index'); // dont care about this...
// what I need is a way to do this:
$res = $controller->sendMail("bla", "bla"); // so that I can test sendMail?
}
}
How can I test sendMail?
You dont actually need to call the dispatch method, you can new up a controller object and call methods directly:
$controller = new \My\Controller();
$actual_result = $controller->sendMail($params);
$this->assertEquals($expected_result, $actual_result);
Be careful though, you'll need to 'mock' your dependencies so you don't actually send a real email when you run your tests! http://phpunit.de/manual/3.0/en/mock-objects.html

How to call custom filters in Zend?

I want to use htmlpurifier on my website, but can't figure out how to load my filter in the view. I've added my filter the way described in the first answer here.
I want to be able to call it from my view with something like $this->filter($content) Any suggestions how I do that?
It is a two step process:
Write an actual Zend_Filter implementation of HTMLPurifier (done, answer in the question you mentioned)
Write a view helper
It will look like this:
class My_View_Helper_Purify extends Zend_View_Helper_Abstract
{
public function purify($value)
{
$filter = new My_Filter_HtmlPurifier();
return $filter->filter($value);
}
}
Don't forget to add your custom view helper path:
$view->addHelperPath(
APPLICATION_PATH . '/../library/My/View/Helper',
'My_View_Helper_'
);
And later in any of your view scripts:
<?= $this->purify($text) ?>

How does the session state work in MVC 2.0?

I have a controller that stores various info (Ie. FormID, QuestionAnswerList, etc). Currently I am storing them in the Controller.Session and it works fine.
I wanted to break out some logic into a separate class (Ie. RulesController), where I could perform certain checks, etc, but when I try and reference the Session there, it is null. It's clear that the Session remains valid only within the context of the specific controller, but what is everyone doing regarding this?
I would imagine this is pretty common, you want to share certain "global" variables within the different controllers, what is best practice?
Here is a portion of my code:
In my BaseController class:
public List<QuestionAnswer> QuestionAnswers
{
get
{
if (Session["QuestionAnswers"] == null)
{
List<QuestionAnswer> qAnswers = qaRepository.GetQuestionAnswers(CurrentSection, UserSmartFormID);
Session["QuestionAnswers"] = qAnswers;
return qAnswers;
}
else
{
return (List<QuestionAnswer>)Session["QuestionAnswers"];
}
}
set
{
Session["QuestionAnswers"] = value;
}
}
In my first Controller (derived from BaseController):
QuestionAnswers = qaRepository.GetQuestionAnswers(CurrentSection, UserSmartFormID);
I stepped through the code and the above statement executes fine, setting the Session["QuestionAnswers"], but then when I try to get from another controller below, the Session["QuestionAnswers"] is null!
My second controller (also derived from BaseController):
List<QuestionAnswer> currentList = (List<QuestionAnswer>)QuestionAnswers;
The above line fails! It looks like the Session object itself is null (not just Session["QuestionAnswers"])
does it make a difference if you retrieve your session using
HttpContext.Current.Session("mySpecialSession") ''# note this is VB, not C#
I believe TempData will solve your problem, it operates with in the session and persists across multiple requests, however by default it will clear the stored data once you access it again, if that's a problem you can tell it to keep the info with the newly added Keep() function.
So in your case:
...
TempData["QuestionAnswers"] = qAnswers;
...
There's much more info at:
http://weblogs.asp.net/jacqueseloff/archive/2009/11/17/tempdata-improvements.aspx
Where are you accessing the session in the second controller? The session object is not available in the constructor because it is injected later on in the lifecycle.
Ok, finally got it working, although a bit kludgy. I found the solution from another related SO post.
I added the following to my BaseController:
public new HttpContextBase HttpContext
{
get
{
HttpContextWrapper context =
new HttpContextWrapper(System.Web.HttpContext.Current);
return (HttpContextBase)context;
}
}
Then set/retrieved my Session variables using HttpContext.Session and works fine!