zf2 display module action in another module - zend-framework2

Hi I created two modules first application second comment.
Idea is to use comment module(Widget) in any application action (website page).
Application module
Test controller
public function commentAction(){
//seting redirection for form
$this->getCommentService()->setRedirection('test/comment');
$list = $this->forward()->dispatch('comment_controrller', array('action' => 'list'));
$add = $this->forward()->dispatch('comment_controrller', array('action' => 'add'));
$view = new ViewModel();
$view->addChild($list, 'list');
$view->addChild($add, 'add');
return $view;
}
View
Comment module
Comment controller
public function addAction()
{
$form = new CommentForm();
$form->get('submit')->setAttribute('value', 'Add');
$request = $this->getRequest();
if ($request->isPost()) {
$comment = new Comment();
$form->setInputFilter($comment ->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$comment ->exchangeArray($form->getData());
$this->getCommentTable()->saveComment($comment);
// Redirect to test controller in application module
return $this->redirect()->toRoute($this->getCommentService()->getRedirection());
}
}
return array('form' => $form);
}
public function listAction()
{
return new ViewModel(array(
$list=> 'test'
));
}
With simple variable (list) all working fine,
Problem I get when trying to redirect form back to comment action in test controller
I can add redirection to test/comment in case form is not valid
but how I will pass all validating errors to test/comment(form)
Can you tell me, if what I'm doing logically correct or in ZF2 we have different way to do widgets

Thanks for help
Answer from weierophinney
http://zend-framework-community.634137.n4.nabble.com/zf2-widget-base-app-logic-td4657457.html
This what I've got so far:
https://github.com/nsenkevich/comment

Related

ZF2 : paramaters coming from route are cleared after submitting a form

I'm using AbstractTableGateway and HydratingResultset to do db operations. (with BjyProfiler)
when i post my form data with add action it works, but edit action doesn't work. when i make a bind it works, but i m redirected to the add page because submitting the form resets paramaters coming from route.
here is my code for editAction() (same with Album editAction())
$id = (int)$this->params()->fromRoute('id');
if (!$id) {
return $this->redirect()->toRoute('voyage', array('action'=>'add'));
}
$voyage = $this->getVoyageTable()->getVoyage($id);
$form = new VoyageForm($this->getTypeVoyageTable());
$form->bind($voyage);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getVoyageTable()->saveVoyage($voyage);
// Redirect to list of voyages
return $this->redirect()->toRoute('voyage');
}
}
return array(
'id' => $id,
'form' => $form,
);
}
and my table :
class VoyageTable extends AbstractTableGateway
{
protected $table ='voyages';
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
$this->resultSetPrototype = new HydratingResultSet();
$this->resultSetPrototype->setObjectPrototype(new Voyage());
$this->initialize();
}
[...]
Can sombody help me? How can i fix this problem ? Thanks.
You need to inform the form about the hydrator since ClassMethods is not the default
$form->setHydrator(new ClassMethods());

ZF2 - Register/Login overlay in it's own action, JS to open and possible to deep link

I have overlays and a hidden panel on my site which uses AJAX to pull in content from another controller/action. You click a link which pushState the URL and AJAX pulls in the content with setTerminal(true); so there is no layout wrapped around. These overlay/hiddenpanels are login/register and would also like them to already be in HTML when you request the page without ajax (refresh) so they can be deeplinked to.
Currently I have something like this in the register controller/action:
public function registerAction () {
$request = $this->getRequest();
// Possible $form = new RegisterForm(); with validation and error population etc
// If we're not requesting via AJAX, forward dispatch to index
if (!$request->isXmlHttpRequest()) {
return $this->forward()->dispatch('index', array(
'action' => 'index',
'overlay' => 1
));
}
$view = new ViewModel();
$view->setTerminal(true);
return $view;
}
If there isn't an XmlHttpRequest then it forward dispatches to index/index with the following check:
public function indexAction () {
$routeRequest = $this->getEvent()->getRouteMatch();
$view = new ViewModel([]);
// Check if user went to somewhere like register page
$overlay = $routeRequest->getParam('overlay', null);
if (null !== $overlay) {
$view->overlay = true;
}
return $view;
}
In my layout I'm checking if the view has the overlay view variable set and then including the overlay in HTML for the previous action like so (controllerName and actionName ViewHelpers get populated onBootstrap so contain register as controller etc):
// Layout.phtml
if ($viewVariables->overlay) {
echo $this->partial('application/' . $this->controllerName() . '/' . $this->actionName() . '.phtml');
}
But this currently doesn't contain any data from the registerAction. I was thinking of having a registration form and having everything registration related done inside there as well and having it accessible where-ever I might forward dispatch to but now it's getting rather complex forwarding and passing variables about.
I was thinking of creating a ViewHelper like echo $this->overlay() which would contain ViewVariables from the previous view and include the other view as a partial but then also thought about passing the view from registerAction to indexAction via the forward dispatcher and nesting it.
Right now i'm triggering statechange with JS at the bottom of the page which takes the current URL and grabs it via AJAX but making the user wait for a full page render and then loading symbol after that is confusing when it can already be there.
This seems a rather complex problem as I'm not too familiar with what's available. I'm seeing alot of modules with the eventManager so am wondering how others would approach this?
Managed to do this and it was easier than I expected.
// RegisterController/indexAction
public function registerAction()
{
$request = $this->getRequest();
$view = new ViewModel();
// If we're not requesting via AJAX, forward dispatch to index
if (!$request->isXmlHttpRequest()) {
$view->setTemplate('application/register/index');
return $this->forward()->dispatch('index', array(
'action' => 'index',
'overlay' => $view
));
}
$view->setTerminal(true);
return $view;
}
// IndexController/indexAction
public function indexAction()
{
$request = $this->getRequest();
$routeRequest = $this->getEvent()->getRouteMatch();
$view = new ViewModel();
$overlay = $routeRequest->getParam('overlay', null);
if (null !== $overlay) {
$view->addChild($overlay, 'overlay');
}
return $view;
}
My only gripe with this is that I have to manually set the template for the child view before I forward dispatch it, as it gets populated onDispatch with a default path if none was specified.
public function registerAction () {
$request = $this->getRequest();
// Possible $form = new RegisterForm(); with validation and error population etc
// If we're not requesting via AJAX, forward dispatch to index
if (!$request->isXmlHttpRequest()) {
return $this->forward()->dispatch('index', array(
'action' => 'index',
'overlay' => 1
));
}
$view = new ViewModel();
$view->setTerminal(true);
return $view;
}

ZF2 Service Locator

I'm quite new to zf2 and I'm experimenting with it. I have a view helper and I need it to access a table object. In my controller I can run:
$this->getServiceLocator();
But ideally I would run this inside my view helper. Unfortunately, I can't seem to access it from within my view helper. I tried passing it through the constructor, configuring a factory method in module.config.php, but when I try that, Zend will no longer pass a tablegateway object into one of my model objects created from a service factory method in the module's Module.php file. This seems to be because it no longer calls the factory method, and opts to run instantiate without any parameters.
I'm not certain I understand why the view factory methods would affect a different set of factory methods with different names.
Can anyone tell me what is wrong with what I'm doing? I can provide more details, but at this point I'm unclear on what details are actually important without supplying the entire codebase.
Thanks.
Crisp does provide a valid answer to your question, but I would suggest to take it one step further. The injection of the service locator makes your view helper tightly coupled to the framework and service locator pattern and vulnerable because every piece of code inside your application can modify every service in the service locator.
There are reasons to inject your dependency directly, so you only depend on your dependencies and you're not implementing this anti-pattern anymore. Let's assume your view helper depends on MyModule\Model\MyTable, then the constructor of your view helper would just look like this:
namespace MyModule;
use MyModule\Model\MyTable;
use Zend\View\Helper\AbstractHelper;
class MyViewHelper extends AbstractHelper
{
protected $table;
public function __construct(MyTable $table)
{
$this->table = $table;
}
}
As you pointed out, you just inject your MyTable now:
namespace MyModule;
class Module
{
public function getViewHelperConfig()
{
return array(
'factories' => array(
'MyViewHelper' => function($sm) {
$sm = $sm->getServiceLocator(); // $sm was the view helper's locator
$table = $sm->get('MyModule_MyTable');
$helper = new MyModule\View\Helper\MyHelper($table);
return $helper;
}
)
);
}
}
Note that inside a view helper factory your service manager is the view helper's service manager and not the "main" one where the table is registered (see also a blog post of I wrote earlier). The $sm->getServiceLocator() solves this for you.
I'm not certain I understand why the view factory methods would affect a different set of factory methods with different names.
It's not, so there is probably a bug in your code. If above does not work, please provide some more details on your service manager configuration so I can update my answer.
One of the great advantages of above approach is you make unit testing really easy for your view helper. You can mock the table gateway and focus on the complete behaviour of your view helper.
use MyModule\View\Helper\MyHelper;
public function testHelperusesTable
{
$mock = $this->getMock('MyModule\Model\MyTable');
$helper = new MyHelper($mock);
// Test your $helper now
}
You can inject the service locator into your view helper from the view helper config in Module.php
// Application/Module.php
public function getViewHelperConfig()
{
return array(
'factories' => array(
'myViewHelper' => function ($serviceManager) {
// Get the service locator
$serviceLocator = $serviceManager->getServiceLocator();
// pass it to your helper
return new \Application\View\Helper\MyViewHelper($serviceLocator);
}
)
);
}
In your view helper
<?php
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper,
Zend\ServiceManager\ServiceLocatorInterface as ServiceLocator;
class MyViewHelper extends AbstractHelper
{
protected $serviceLocator;
public function __construct(ServiceLocator $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
}
While working in Zend Framework,we often need custom helper,that make our work easy, In zf1 accessing database model from helper was easy,but i got stuck that how to access database model for any table in Custom View Helper, but as i was needing it i get around through the problem in unprofessional way by creatina new db adapter object in the view, which was never good way, but recently i came to know through very interesting way to access the database adapter in the view helper and there i have to execute any query on any table, it may be not so Zend F2 way, but very simple and short way to solve the issue.
Here is my Model Example...
<?php
namespace Application\Model;
use Zend\Db\TableGateway\TableGateway;
class SlideImageSubTable {
protected $tableGateway;
public $adapter;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
$this->adapter = $this->tableGateway->getAdapter();
}
public function fetchAll() {
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getSlideImageSub($id) {
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function getImageMenu($id) {
$id = (int) $id;
$rowset = $this->tableGateway->select(array('slide_image_id' => $id));
$rows = array_values(iterator_to_array($rowset));
if (!$rows) {
throw new \Exception("Could not find row $id");
}
return $rows;
}
public function saveSlideImageSub(SlideImageSub $slideImageSub) {
$data = array(
'slide_image_id' => $slideImageSub->slide_image_id,
'title' => $slideImageSub->title,
'description' => $slideImageSub->description
);
$id = (int) $slideImageSub->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getSlideImageSub($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Form id does not exist');
}
}
}
public function deleteSlideImageSub($id) {
$this->tableGateway->delete(array('id' => $id));
}
}
Just look at the 'public $adapter' public variable. And in the constructor i am going to initialize it by calling $this->tableGateway->getAdapter(); method, getAdapter() is available thorugh gateway object.
Then in my controller action view, i have to assign it to any variable and pass that variable to view page. like this..
public function equitiesAction() {
$image_id = $this->params('id');
$result = $this->getTable('SlideImageSub')->getImageMenu($image_id);
$adapter = $this->table->adapter;
$view = new ViewModel(array(
'result' => $result,
'adapter' => $adapter,
));
return $view;
}
And in the view i pass the 'adapter' object to custom view like this..
<?php echo $this->GetMenuProducts( $this->adapter); ?>
Now in custom view i can use this database adapter object and create select query on any table.
Hope this will help someone, i look around for using database access in custom view helper but the configurations methods provided was not working for me.
Thanks
$this->getView()->getHelperPluginManager()->getServiceLocator();

How to render a different view in controller action of ZF2

How to render a different view other than default in controller action. by default it try to find the same view as action in the view folder but I would like render different view available in views folder for controler action.
We can do this ZF1 like this $this->_helper->viewRenderer('foo');
Can Anyone know, how to achieve above in Zendframework 2?
We can disabled the view using
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent("Hello World");
return $response;
I don't know how to change/render a different view in zf2.
can be done using
public function abcAction()
{
$view = new ViewModel(array('variable'=>$value));
$view->setTemplate('module/controler/action.phtml'); // path to phtml file under view folder
return $view;
}
Thanks to akrabat for covering almost every scenario.
My solution in Zend Framewor 2 is simple. For index action i prefer to call parrent::indexAction() constructor bcs we extend Zend\Mvc\Controller\AbstractActionController . Or just return array() in indexAction. ZF will atomaticly return index.pthml whitout definig what must be returned.
return new ViewManager() is the same return array()
<?php
namespace Test\Controller;
use Zend\Mvc\Controller\AbstractActionController,
Zend\View\Model\ViewModel;
// Or if u write Restful web service then use RestfulController
// use Zend\Mvc\Controller\AbstractRestfulController
class TestController extends AbstractActionController
{
/*
* Index action
*
* #return main index.phtml
*/
public function indexAction()
{
parent::indexAction();
// or return new ViewModel();
// or much simple return array();
}
/*
* Add new comment
*
* #return addComment.phtml
*/
public function addAction()
{
$view = new ViewManager();
$view->setTemplate('test/test/addComment.phtml'); // module/Test/view/test/test/
return $view;
}
Dont forget to configure route and view_manager in module/config/module_config
'view_manager' => array(
'template_path_stack' => array(
'Test' => __DIR__ . '/../view',
),
),

Symfony admin generator : add user id before saving

I'm creating my own blog engine to learn Symfony, and I have a question :
In the generated administration pages for a blog post, I have a drop-down list of authors, to indicate the author_id.
I'd like to hide that drop-down list, and set the author_id to the id of the current logged-in user when the post is created (but not when it is edited)
How can I accomplish that ?
Edit
I've tried those :
$request->setParameter(sprintf("%s[%s]", $this->form->getName(), "author_id"), $this->getUser()->getAttribute("user_id"));
$request->setParameter("content[author_id]", $this->getUser()->getAttribute("user_id"));
$request->setParameter("author_id", $this->getUser()->getAttribute("user_id"));
$request->setParameter("author_id", 2);
$request->setParameter("content[author_id]", 2);
$request->setParameter("author_id", "2");
$request->setParameter("content[author_id]", "2");
In processForm() and executeCreate()
Resolved !
The final code is :
public function executeCreate(sfWebRequest $request)
{
$form = $this->configuration->getForm();
$params = $request->getParameter($form->getName());
$params["author_id"] = $this->getUser()->getGuardUser()->getId();;
$request->setParameter($form->getName(), $params);
parent::executeCreate($request);
}
Override the executeCreate function in the actions file. When binding post data to the form, merge the current user's id into it.
2nd update
I did some experimenting, and this works:
class fooActions extends autoFooActions
{
public function executeCreate(sfWebRequest $request)
{
$form = $this->configuration->getForm();
$params = $request->getParameter($form->getName());
$params["author_id"] = 123;
$request->setParameter($form->getName(), $params);
parent::executeCreate($request);
}
}
change the widget in the form with the sfWidgetFormInputHidden and set the value with sfUser attribute (that defined when a user logged in)
override the executeCreate() and set the author_id widget (thanks to maerlyn :D )
public function executeCreate(sfWebRequest $request){
parent::executeCreate($request);
$this->form->setWidget('author_id', new sfWidgetFormInputHidden(array(),array('value'=>$this->getUser()->getAttribute('author_id'))) );
}
In Objects , the solution is: (new and $this)
class fooActions extends autoFooActions
{
public function executeCreate(sfWebRequest $request)
{
$this->form = new XxxxxForm();
$params = $request->getParameter($this->form->getName());
$params["author_id"] = 123;
$request->setParameter($this->form->getName(), $params);
parent::executeCreate($request);
}
}

Resources