zend2 check if homepage - zend-framework

How to check if current page is homepage? In my header i want to show something only on homepage.
$header = new ViewModel(array(
'login' => $this->getAuthService()->hasIdentity(),
'controller' => $this->getRequest()->getControllerName(),
'action' => $this->getRequest()->getActionName()
));
In my view i have tried to find the homepage by finding index controller and index action but this is not working.
<?php
if($this->controller = 'index' && $this->action = 'index') {
echo 'home';
}
else {
echo 'not';
}
?>

Take a look at this ViewHelper or that get matched route in view.

You have to test if your called url is your "home" route. You cant test it by controller or action name because you could have more than one IndexController and indexAction. But you coul only have one route "home".

Related

can't pass parameter from view to controller

Hi all I am currently working with zend 2.3. and while listing students I am trying to make link that allows to show detales about selected person. My problem is that I can't pass selected id to the action in module's controller. Here is my view's code that coresponds to link:
<a href="<?php echo $this->url('admin' ,
array( 'controller'=>'Admin', 'action'=>'viewstudent', 'ID' => $student->ID))."/admin/viewstudent";?>">detales</a>
and the action in controller
public function viewstudentAction ()
{
$id = (int) $this->params()->fromRoute('ID', 0);
echo $id;
//echo var_dump($id);
return new ViewModel(array(
'students' => $this->getStudentTable()->viewstudent($id),
));
}
Then I var_dump $id variable it shows 0 So what is the correct way to do this?
I have edited the a href's code like this
<a href="<?php echo $this->url('admin/default' ,
array( 'controller'=>'Admin', 'action'=>'viewstudent', 'id' => $student->ID));?>">Просмотр</a>
and it resolves to this:
Просмотр
url is
http://localhost:8080/disability/public/admin/Admin/viewstudent
The url is
http://localhost:8080/disability/public/admin/Admin/viewstudent
Problem is the same id didn't pass
I have found the solution to the problem. I passed the parameter using query here is how it looks in view file
<a href="<?php echo $this->url('admin/default',
array('controller' => 'Admin',
'action'=>'viewstudent'
),
array('query' =>
array('id' => $student->ID)
)
);
?>">view</a>
And then using $this->params retrieve it in my controller file
$id = $this->params()->fromQuery('id');

Zend Framework 2 - Including a variable in a form action

My login form may be called with a re-direct query and I am wondering if there is a simple way to include this in the subsequent post action.
The use case is for SSO login.
My normal login route is:
/customer/login
and when called from a third party client becomes:
/customer/login?redirectTo=http://www.example.com
My login action:
public function loginAction()
{
$prg = $this->prg();
if ($prg instanceof Response) {
return $prg;
} elseif ($prg === false) {
return new ViewModel(['form' => $this->loginForm]);
}
This loads my view and I currently define my action as so:
$form = $this->form;
$form->setAttribute('action', $this->url());
Now when the action is called, I am losing the redirectTo parameter.
So my question is this, is it possible to update the action to include the re-direct url so that when a user clicks to login, it is posted back to my form?
thanks!
EDIT -
Obviously I can create a redirectTo route in the configs and test on the initial call to the page for the existence of such a route and include this in the form. My question however is whether or not this can be done automagically simply from the viewscript.
To generate query string arguments from the view helper, you need to assign them as the third argument using the query key. Please refer to the ZF2 docs http://framework.zend.com/manual/current/en/modules/zend.view.helpers.url.html
$form->setAttribute('action', $this->url('application', array('action' => 'login'), array('query' => array('redirectTo' => 'http://www.example.com,))));
$form->setAttribute('action', $this->url('login', [
'query' => [
'redirectTo' => $this->params()->fromQuery('redirectTo')
]
]);
Where 'login' is the name of the login route.
See Url View Helper
Well my solution is not as elegant as I hoped it would be. I wanted to avoid using the controller for the query params. As #Stanimir pointed out, the view helpers are in fact, to help with view so my original idea was unfounded.
This is an end to end of what I have put together:
Controller:
$redirect_url = $this->params()->fromQuery('redirectTo',null);
Returns this to view on initial load:
return new ViewModel( ['form' => $this->loginForm , 'redirect_url' => $redirect_url] );
View
$form->setAttribute(
'action',
$this->url(
'customer/login', [] ,
[ 'query'=>
[ 'redirectTo' => $this->redirect_url ]
]
)
);

Zend: Redirect from form without validation

I have a form for the creation of new "groups". I now added a small "go back" image with which the user should be able to go back one step. I don't know why, but when I click this new image, the controller and action used for the form which I want to leave (/admin/creategroup) is called again with HTTP POST set. Therefore, the form validation is done, and I'm stuck at this form with the validation errors displayed.
This is a snippet of the code from my form with both image-buttons. I wan't the "go back"-image to redirect me to the specified controller without validating the form:
$this->addElement('image', 'btnBack', array (
'name' => 'btnBack',
'id' => 'btnBack',
'label' => '',
'title' => 'Go back',
'alt' => 'Go back',
'src' => '/img/undo.png',
'onClick' => "window.location='/admin/groupoverview'"
));
$this->addElement('image', 'btnSave', array (
'name' => 'btnSave',
'id' => 'btnSave',
'label' => '',
'title' => 'Save this new group',
'alt' => 'Save this new group',
'src' => '/img/save.png',
'onClick' => "document.forms[0].submit();"
));
Edit:
I already thought of the possibility to check in /admin/creategroup whether it was called from the 'btnBack'-image or the 'btnSave'-image and skip form validation and redirect correctly if the source was the 'btnBack'-image.
I just think that there should be a nicer solution to directly redirect from the form and circumvent calling /admin/creategroup again.
Edit2:
My view script:
<div id="createGroupMask">
<br/>
Use the form below to create a new group
<?php
$this->form->setAction($this->url());
echo $this->form;
?>
</div>
My action in the controller:
public function creategroupAction()
{
$form = new Application_Form_CreateGroup();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
// Data for new group is valid
...
} else {
// Form data was invalid
// => This is where I land when pressing the 'back' image
// No further code here
}
}
$this->view->form = $form;
}
Now there is something to work with:
The isValid() loop is incorrect, your form will never evaluate as inValid with respect to the elements you've presented, you will never get to the else.
public function creategroupAction()
{
$form = new Application_Form_CreateGroup();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
// Data for new group is valid
...
} else {
/* This is incorrect */
// Form data was invalid
// => This is where I land when pressing the 'back' image
// No further code here
}
}
$this->view->form = $form;
}
My problem is that I'm not sure what is going to be submitted from your form, I'm not really familiar with how your using "onClick" and what I presume is javascript. It looks like element btnBack should redirect on click and element btnSave should POST. However this does not seem to be happening.
I have done this type of thing in PHP and ZF with submit buttons, perhaps the flow of what I did will help:
NOTE: for this type of flow to work you must give the button element a label. The label is used as the submit value.
//psuedoCode
public function creategroupAction()
{
$form = new Application_Form_CreateGroup();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
//I would probably opt to perform this task with a switch loop
if ($form->getValue('btnBack') === some true value) {
$this->_redirect('new url');
}
if ($form->getValue('btnSave') === some true value) {
//Process and save data
}
} else {
//Display form errors
}
$this->view->form = $form;
}
I think when all is said and done the crux of your problem is that you did not give your button elements a label.
I tried adding labels to my images, but this didn't work.
I also tried to use the isChecked() method on my btnBack-image like this:
if ($form->btnBack->isChecked()) {
// 'Go back' image was clicked so this is no real error, just redirect
}
This didn't work either.
I finally was able to check which image was clicked via the following method as answered in Zend form: image as submit button:
public function creategroupAction()
{
$form = new Application_Form_CreateGroup();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
// Data for new group is valid
...
} else {
// Form data was invalid
if (isset($this->_request->btnBack_x)) {
// 'Go back' image was pressed, so this is no error
// -> redirect to group overview page
$this->_redirect('/admin/groupoverview');
}
}
}
$this->view->form = $form;
}
I guess this doesn't thoroughly answer the original question as the validation is still done and I'm only checking for this 'special case' where the 'Go back' image was clicked, but I'll mark it as answered anyways.
Tim Fountain suggested an even cleaner approach in my somewhat related question:
Zend forms: How to surround an image-element with a hyperlink?

ZF strange layout behavior

I have a strange behavior with ZF that I can't resolve. I have a layout.phtml and a login.phtml. So when the user is logged in the layout.phtml should be displayed else the login.phtml. This also works, but before displaying the login.phtml, ZF go through layout.phtml and I can confirm this due to errors in the error.log file.
Here what I have in the bootstrap:
public static function _initAcl()
{
$auth = Zend_Auth::getInstance();
$acl = new BM_Acl($auth);
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(
new BM_Controller_Plugin_Acl($auth, $acl)
);
}
Here what I have in the auth controller:
public function indexAction() {
$form = new BM_Form_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
if ($this->_process($form->getValues())) {
// We're authenticated! Redirect to the home page
//json validation on login page
$var = json_encode(array('valid' => true, 'redirect' => 'index'));
echo $var;
exit();
} else {
$var = json_encode(array('valid' => FALSE, 'error' => 'Authentication failed!', 'redirect' => 'auth'));
echo $var;
exit();
}
}
}// end if is POST
$this->_helper->layout()->setLayout('login'); // special login page
$this->view->form = $form;
}
Any help will be appreciated...
Regards
Andrea
P.S. This only happens when I start the application from a new browser window. If I refersh the login page, the layout is not called anymore...
Views are for single pages. If you have a singular page you wish to display with a template like layout.phtml, you would edit the index.phtml inside the index action's views directory. If you want to disable the main layout
$this->_helper->layout()->disableLayout();
Or use a blank layout
$this->_helper->layout()->setLayout('blank');
Any code specific to a singular page should be done with a view.
Iam not sure, but the i think the layout is redered before the view scripts. You could try to put you logic inside the preDispatch Hook in your Controller.
public function preDispatch() {
$form = new BM_Form_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
if ($this->_process($form->getValues())) {
// We're authenticated! Redirect to the home page
//json validation on login page
$var = json_encode(array('valid' => true, 'redirect' => 'index'));
echo $var;
exit();
} else {
$var = json_encode(array('valid' => FALSE, 'error' => 'Authentication failed!', 'redirect' => 'auth'));
echo $var;
exit();
}
}
}// end if is POST
$this->_helper->layout()->setLayout('login'); // special login page
$this->view->form = $form;
}
Or use an ControllerPlugin:
Zend Controller Plugin - Doc
When I understand right, you have a layout that you use on all pages, except for login. Instead of using the view for login as a layout, you should disable layout for this action and just render the login.phtml normally. You can do this by calling the following in your controller's loginAction, instead of setLayout('login'):
$this->_helper->layout()->disableLayout();
This will just disable the layout, but the view is rendered normally.
If you want to do it your way, you have to place the login.phtml into the layout-path, not in the view-path (if you want a more detailed explanation, just ask in a comment).

cakephp auth component allow redirect issue

I am having problem with Auth component when I use $this->Auth->allow('index','view');
I am getting /users/login has resulted in too many redirects when I use $this->Auth->allow('*') it works fine. I am using cakephp 1.3.12 here is app_controller.php
class AppController extends Controller {
var $components = array('Auth','Session');
function beforeFilter(){
$this->Auth->allow('index','view');
}
}
I changed the app_controller.php
class AppController extends Controller {
var $components = array('Auth','Session');
function beforeFilter(){
$this->Auth->allow(array('index','view','display'));
}
}
users_controller.php
class UsersController extends AppController {
var $name = 'Users';
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('login','logout'));
}
function login() {
if ($this->Session->read('Auth.User')) {
$this->redirect('/', null, false);
}
}
routes.php
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
any suggestions?
Thanks
Don't know but you might want to check if you have any request actions.
"If you are using requestAction in your layout or elements you should allow those actions in order to be able to open login page properly."
http://book.cakephp.org/1.3/en/view/1257/allow
This had me stumped for the longest time.
Let's say you render an element somewhere in your template:
echo $this->element('comments');
And in views/elements/comments.ctp you have something that requests an action like
$comments = $this->requestAction('comments/index');
foreach($comments as $comment) {
// print stuff
}
In your CommentsController your have to:
function beforeFilter() {
$this->Auth->allow('index');
}
Notice you are requesting an index action from your comments controller in your element. That's why you have to allow 'index' for that specific controller.
I haven't seen this problem properly addressed anywhere. Hope that's what is causing your error.
its an array =)
$this->Auth->allow(array('index','view'));
your getting the too many redirects message becasuse the /user/login action is not accessible. So the server tries to display the login page, but it can't, because regular non-connected users dont have acces to /user/login. And when a user doesn't have access to a page, the server will redirect him to the login page... so you see, its an infinite loop.
The /user/login action should be authorized to everyone. Your Users controller should look like this:
class UsersController extends AppController {
var $name = 'Users';
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('login','logout'));
}
function login(){
if ($this->Session->read('Auth.User')) {
$this->redirect('/', null, false);
}
}
//if you're using prefix routes.
function admin_login(){
$this->redirect('/users/login');
}
if this doesn't the problem, maybe you're redirecting the page in the routes.php
Hope this helps
you are doing it wrong.How can app can get to know that which of your controller action you are trying to controller.Do it from your controller.
remove this from app
$this->Auth->allow(array('index','view','display'));
try this in your app controller with needed change
$this->Auth->loginError = "Wrong credentials. Please provide a valid username and password.";
$this->Auth->authError = "You don't have sufficient privilege to access this resource.";
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'dashboard');
do this from your user controller
$this->Auth->userModel = 'User';
$this->Auth->allow('*');
And in your login dont do anything all of your redirect and all will be doing by app controller.
If you have any doubt regarding this mail me
jafarkv9#gmail.com