Yii2 make session works on all actions of one controller? - yii2

In my SiteContoller I need to access the session on almost every action.
but I find write
$session = Yii::$app->session;
$session->open();
duplicate the same code on every action of the same controller is annoying.
anyway to solve this???

If you want to have your session opened in only SiteContoller you need to open it in before action method as so:
public function beforeAction($action) {
Yii::$app->session->open();
return parent::beforeAction($action);
}

Related

Running yii2 script using task scheduler

I want to run my action method in yii2 advanced automatically. I put the code on the console/controllers. This is the code:
MailController.php
<?php
namespace console\controllers;
use Yii;
use yii\console\Controller;
use Swift_TransportException;
class MailController extends Controller
{
public function actionSend()
{
$mail = Yii::$app->mailer->compose()
->setFrom('if414024#students.del.ac.id')
->setTo('if414024#students.del.ac.id')
->setSubject('Testing');
try
{
$mail->send();
}
catch (Swift_TransportException $ste)
{
echo 'error';
}
}
}
?>
Then I make this configuration from actions menu in task scheduler:
Program/script: C:\xampp\php\php.exe
Add arguments (optional) : -f C:\xampp\htdocs\Baru\advanced\console\controllers\MailController.php
I want to run send action. But the result in task scheduler is 0xFF and I don't get the email. What's the problem?
You need to call the controller action this way:
C:\xampp\php\php.exe c:\path\to\your\application\yii mail/send
or
c:\path\to\your\application\yii.bat mail/send
You are calling yii, and not the controller script directly. The controller and action (the route) is just a parameter.
See here or the guide for more information.

Kohana 3 sessions between functions

I am trying to use session in controller between functions in Kohana 3:
public function action_setsession()
{
$session = Session::instance();
$session->set('test1', 'testing1');
$session->set('test2', 'testing2');
}
public function action_getsession()
{
$session = Session::instance();
$test1 = $session->get('test1');
$test2 = $session->get('test2');
echo 'Test1='.$test1;
echo 'Test2='.$test2;
}
And I do not get any data in getsession() function. Is it possible to use it in this way at all ? Or what I am doing wrong ? Thanks.
I can't see anything wrong with your code. It should work properly but there are some things to check:
Are you running action_setsession before you run action_getsession
Did you configure your session library properly? See Session Configuration
If you checked these things you most likely find the reason why it's not working.

Set Header as 'application/json' to all actions in controller YII

I am creating a rest api using yii framework so the basic output format would be json....
I want all actions in a controller to have header content-type as 'application-json'.
I tried to put it in beforeFilter function in the controller but it didn't work.
Can any one help me out...
Create an init() function in the Controller class (protected/components/Controller.php). This will be called when any Controller/Action is called. Eg:
public function init(){
if ($this->id == 1){
// perform controller specific function
}
}
The $this->id returns the controller id. You must obviously replace the 1 in the code above with the relevant controller id for the controller you want the function to take place with

A plain HTML Submit button passes to the controller only after the second click

I have many submit buttons in my plain HTML . The one not working is as below:- the other are as same as below
< form:submit cssClass="action-button" name="excelBTNX" value="Excel" id="excelBTNX" />
The function of the above button in the controller is to create a excel sheet and put in session(I can download it from cookies ) and returns back .
The defination of the corrosponding method in Controller is as same as for other buttons which are working fine .
The problem with this is ,it works only at even count hit .When I click for the first time the page gets refreshed . When I click for the second time , control passes to the controller and my excel comes up as cookies.
I tried to track whether the submit is working or not with javaScript code as
$(‘form’).submit(function(){
alert("event getting fired");
});
and it gives the alert for both the cases.
I have done the validation part from the controller(manually), so local inbuilt validators are not used . So I believe they are not the case.
How do I fix it ?
Controller codes:-
#RequestMapping(value = "execute.action", method = RequestMethod.POST, params = "excelBTNX")
public String excelOut(HttpServletRequest request, HttpServletResponse response,
#ModelAttribute("mymodel") myModel model, BindingResult bindingResult, ModelMap modelmap) {
scr14(request).initializeSomeCalculation(model);// some innercalss called to manupulate model
HttpSession session = request.getSession(false);
if(1=1){//CRUD condition here true in READ mode.
model= new myModel ();
}
byte[] excel = createExcelS14(model,request);
String fileName = getExcelName() + ".xls";
String filepath = myFrameWorkUtils.createTempFile(excel, fileName);
if (session != null) {
session.setAttribute(fileDownload, filepath);
}
scr14(request).initializeSomeCalculation(model);
model.setDate(somedate);
return "myPanel";}
Here are some steps:
Check whether this issue is related to your Excel processing or whether it is something with your Controller. I assume you have something like
#RequestMapping(..., params = "excelBTNX")
public ModelAndView next(...)
{ <EXCEL FUNCTIONALITY> }
Just comment out the in the Controller and verify that the method is called every time. Please test this a let us know whether this is working.
What happens that makes you think the Controller is only called at the second click? Maybe the signs that you are looking at don't really mean that the controller is only called every second click. Please explain.
Fix if (1=1) code. = in Java is the assignment operator, == is the comparison operator. I assume you want to do a comparison. It also seems like you simplified this part of the code, but it may actually be the problem. Please post the actual code here.
I don't see anything about cookies here. It looks to me like you are creating a temporary Excel file, and setting the name of the file in the session.
session.setAttribute(fileDownload, filepath) cannot work, since the key of the session attribute map is of type String. It should probably be session.setAttribute("fileDownload", filepath).
Can you see whether there is a new temp Excel file generated with each click? You should be able to tell by the timestamp.
This may still not point to the problem, but it will certainly get us closer.

Zend FlashMessenger problems

I am new to Zend framework and I have a problem.
I created a controller abstract class which implements the functions like:
protected function AddError($message) {
$flashMessenger = $this->_helper->FlashMessenger;
$flashMessenger->setNamespace('Errors');
$flashMessenger->addMessage($message);
$this->view->Errors = $flashMessenger->getMessages();
}
protected function activateErrors()
{
$flashMessenger = $this->_helper->FlashMessenger;
$flashMessenger->setNamespace('Errors');
$this->view->Errors = $flashMessenger->getMessages();
}
So for each controller I am able to use
$this->AddError($error);
And then I render $error in layout.
So I want not to deal with flashMesenger in every controller.
but I have to execute the activateErrors when each action is executed.
for example
I have an controller test
class TestController extends MyController {
public function indexAction() {
$this->AddError("Error 1");
$this->AddError("Error 2");
$this->activateErrors();
}
public function index1Action() {
$this->AddError("Esdsd 1");
$this->AddError("sddsd 2");
$this->activateErrors();
}
}
Is there a way that I could execute this activateErrors in each action for every controller at the end of action without duplicating the code.
I mean I do not want to include this code at every action. Maybe there is a way to include it in my abstract class MyController.
Anybody any Idea?
thanks
What about using a postDispatch hook, in your parent MyController ?
Quoting that page :
Zend_Controller_Action specifies two
methods that may be called to bookend
a requested action, preDispatch() and
postDispatch(). These can be useful in
a variety of ways: verifying
authentication and ACL's prior to
running an action (by calling
_forward() in preDispatch(), the action will be skipped), for instance,
or placing generated content in a
sitewide template (postDispatch()).
Maybe this might do the trick ?
I actually contributed an enhancement to FlashMessenger which provides a lot of the functionality you're looking for.