How to disable layout and view renderer in ZF2? - zend-framework

How can i disable layout and view renderer in Zend Framework 2.x? I read documentation and can't get any answers looking in google i found answer to Zend 1.x and it's
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
But it's not working any more in Zend Framework 2.x. I need to disable both view renderer and layout for Ajax requests.
Any help would be great.

Just use setTerminal(true) in your controller to disable layout.
This behaviour documented here: Zend View Quick Start :: Dealing With Layouts
Example:
<?php
namespace YourApp\Controller;
use Zend\View\Model\ViewModel;
class FooController extends AbstractActionController
{
public function fooAction()
{
$viewModel = new ViewModel();
$viewModel->setVariables(array('key' => 'value'))
->setTerminal(true);
return $viewModel;
}
}
If you want to send JSON response instead of rendering a .phtml file, try to use JsonRenderer:
Add this line to the top of the class:
use Zend\View\Model\JsonModel;
and here an action example which returns JSON:
public function jsonAction()
{
$data = ['Foo' => 'Bar', 'Baz' => 'Test'];
return new JsonModel($data);
}
EDIT:
Don't forget to add ViewJsonStrategy to your module.config.php file to allow controllers to return JSON. Thanks #Remi!
'view_manager' => [
'strategies' => [
'ViewJsonStrategy'
],
],

You can add this to the end of your action:
return $this->getResponse();

Slightly more info on the above answer... I use this often when outputting different types of files dynamically: json, xml, pdf, etc... This is the example of outputting an XML file.
// In the controller
$r = $this->getResponse();
$r->setContent(file_get_contents($filePath)); //
$r->getHeaders()->addHeaders(
array('Content-Type'=>'application/xml; charset=utf-8'));
return $r;
The view is not rendered, and only the specified content and headers are sent.

Related

Bootstrapping an extension with Typoscript and calling a specific action

I have build an extension which I am bootstrapping with Typoscript and placing it in a modal box. I also have the same extension included in a Page element but with a different action.
The problem is when calling other actions from the extension in the Page it also reflects what is displayed in the bootstrapped version in the modal box. What I want to do is no matter what arguments are in the URL (which tell the extension what action to execute) the one in the modal box to always call the same action first.
Is this possible?
Should I probably look for a different solution to my problem?
The easiest way in my opinion would be an AbstractContoller from which two different controller inherit.
This way the would be separated completely but could share the same actions:
namespace YOUR\Extension\Controller;
abstract class AbstractController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController{
public function firstAction(){
// your code here
}
public function secondAction(){
// your code here
}
}
First Controller:
namespace YOUR\Extension\Controller;
class FirstController extends AbstractController{
//no need to add actions here
}
Second Controller:
namespace YOUR\Extension\Controller;
class SecondController extends AbstractController{
//no need to add actions here
}
Your typoscript included on the page would then call FirstController->firstAction, the one in the modal would call SecondController->firstAction. If you transfer a different action via GET, it will only affect either the first or the second Controller.
Don't forget:
register the controller/actions in your ext_localconf.php
copy / move the templates accordingly (they need to be in the folders named after the controller, e.g. templates/first/)
Do you call both of your Controller/Action sets in one Plugin?
I would try to split them fe like this
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'VENDOR.' . $_EXTKEY,
'Pluginkey1',
array(
'FirstController' => 'foo, bar',
),
// non-cacheable actions
array(
'FirstController' => '',
)
);
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'VENDOR.' . $_EXTKEY,
'Pluginkey2',
array(
'SecondController' => 'baz',
),
// non-cacheable actions
array(
'SecondController' => '',
)
);

Zend Framework 2 Translating the text of the radio buttons

I´m developing an application using Zend Framework 2 and I need to translate the text of the radio buttons ("Show", "Hide") that I´ve created in my form:
//within the Form
public function addRadioButtons ()
{
$isPublicRadioButtons = new Element\Radio('isPublic');
$isPublicRadioButtons->setAttribute('id', 'isPublic')
->setAttribute('value', '0')
->setValueOptions(array(
'0' => 'Show',
'1' => 'Hide',
));
$this->add($isPublicRadioButtons);
}
What do I have to do in the view side to be able to translate them?
I know that to render translations to the views I need to use $this→translate() view helper. So within the view I´ll have to somehow call the text of the radio buttons..
//Whithin the view
echo $this->translate($someHowCallTheTextOfRadioButton('isPublic') , $textDomain, $locale);
Look at FormLabel section to read about translating labels in zend framework 2. I think that most important thing to remember is:
If you have a translator in the Service Manager under the key,
‘translator’, the view helper plugin manager will automatically attach
the translator to the FormLabel view helper. See
Zend\View\HelperPluginManager::injectTranslator() for more
information.
How to properly setup translator you have in ZendSkeletonApplication
In your view you can do something like this:
$this->formRadio()->setTranslatorTextDomain('textdomainhere');
You can have your form implement the TranslatorAwareInterface and, if you are using PHP 5.4+, have it use the TranslatorAwareTrait (otherwise you simply have to implement the interface yourself). You can now inject a translator instance into your form, e.g. in the form's factory. Then you can translate the labels as follows:
//within the Form
public function addRadioButtons ()
{
$isPublicRadioButtons = new Element\Radio('isPublic');
$isPublicRadioButtons->setAttribute('id', 'isPublic')
->setAttribute('value', '0')
->setValueOptions(array(
'0' => $this->getTranslator()->translate('Show'),
'1' => $this->getTranslator()->translate('Hide'),
));
$this->add($isPublicRadioButtons);
}

Way to define others layout() parts such layout()->content?

Ive done some search but no success.. i am trying to figure out how to define others layout() parts such layout()->content variable.. i would love to get int layout()->navigation (a custom one) which display the navigation..
Any ideas ?
Thanks.
Not sure if this is what you want, but you can create additional 'parts' of layout simply by assigning a value to your new part. ZF will take care of the rest. For example, in a bootstrap.php you could do:
public function _initNewLayoutPart() {
$view = $this->bootstrap('view')->getResource('view');
$view->layout()->newpart = 'some new part';
}
Then in your layout.phtml you could just echo the new part:
<?php echo $this->layout()->newpart; ?>
It is possible by just creating a new variable in layout, you can define it in your controller (preferably in init or postDispatch). Just like this:
public function init()
{
$this->view->layout()->motd = '<b>Message of the day.</b>';
}
Then in your actual view where you want to see the message, all you have to do is:
<?php echo $this->layout()->motd; ?>
If you want something fancier, such as rendering a whole page or sidebar, try the following:
public function init()
{
$this->view->layout()->sidebar = $this->view->action('render', 'sidebar');
}
With render being the action (including render.phtml) and sidebar being the controller.

Zend_Dojo and ValidationTextBox - invalid message does not always appear

I am using Dojo ValidationTextBox through Zend Framework in the following way:
$form->addElement('ValidationTextBox', 'procedureName', array(
'label' => _('Procedure Name'),
'value' => $alarm->procedureName,
'attribs' => array(
'required' => true,
'invalidMessage' => 'Required!'
)
));
Likewise, my form validation is set up in this way:
if (formWidget.isValid()) {
return true;
} else {
alert('Invalid form.');
return false;
}
Form validation will prevent the form from submitting if "procedureName" text box is blank, but Dojo will not mark the form element as invalid, nor display the "Required!" message. In fact, it will mark the form element only if I click it previously (but still, will not display the invalid message).
How can I reconstruct the behavior from this page, where you can click the submit button without clicking on any of required fields previously, and Dojo will mark all required fields?
Thanks.
Dojo allows both declarative and programmatic usage of many of its features.
Declarative usage uses standard HTML elements with non-standard attributes that are parsed when the page is loaded. Can cause issues so Zend Framework uses programmatic usage by default; the various view helpers will generate javascript and push it to the dojo() view helper for inclusion when rendered.
To specify declarative usage, simply call the static setUseDeclarative() method:
Zend_Dojo_View_Helper_Dojo::setUseDeclarative();
When in your form initialization.
This will allow any non standard options like "required" = "true" to be included in your input tag.
dojox.validate function will then work.
I use
<script type="dojo/method" event="onSubmit">
if (this.validate()) {
//return confirm('Form is valid, press OK to submit');
} else {
//alert('Form contains invalid data. Please correct first');
return false;
}
return true;
</script>
inside my form tags as my validation setup.
The error was that I should've used formWidget.validate(), instead of formWidget.isValid().

set/add view from controller action

I'm trying to set a view script to be executed in addition to the currently requested action view script. I want to do this from the controller action itself in a way that this new view script output will be available from the layout $this->layout()->content helper.
I found the setView() method but don't know how to use it from the controller.
Thanks a lot.
If you just want to render some other view script from a controller just:
$this->render('someotherview');
Wich will render someotherview.phtml.
from: http://framework.zend.com/manual/en/zend.controller.action.html#zend.controller.action.viewintegration.render
class MyController extends Zend_Controller_Action{
public function fooAction()
{
// Renders my/foo.phtml
$this->render();
// Renders my/bar.phtml
$this->render('bar');
// Renders baz.phtml
$this->render('baz', null, true);
// Renders my/login.phtml to the 'form' segment of the
// response object
$this->render('login', 'form');
// Renders site.phtml to the 'page' segment of the response
// object; does not use the 'my/' subirectory
$this->render('site', 'page', true);
}
public function bazBatAction()
{
// Renders my/baz-bat.phtml
$this->render();
}
}
Should get you on the right track!
Also
$this->renderScript('path/to/index.phtml');
Works really well.