I am quite new to Zend Framework (2). I have been developing a mini ERP as a project and every thing seemed to be good.
But this morning, I wanted to install PHPUnit, I updated the composer.json file and ran composer install but it saind nothing to install. Then after some brief searches, I noted that I should be running composer update instead. It did update Zend Framework to 2.2.0 and some others. Zend used to be 2.0.8.
I ran the applicaiton, it all looked good, until my partner complained a demo failed.
I diagnosed the problem, which was caused by not loading JavaScript files. The required JavaScripts for the view were given through the controller as follows.
public function viewContactAction(){
// Get the user id from url
$id = $this->params()->fromRoute('id');
$this->headScript = new HeadScript();
$this->headScript->appendFile('../../js/pages/lib/contact.view.js');
$this->headScript->appendFile('../../js/packages/json-populate/dist/jquery.jsonPopulate.min.js');
$view = new ViewModel(array('title' => 'Contact View', 'contact_id' => $id));
$view->setTemplate('contacts/contacts/contact');
return $view;
//die("User View for $id");
}
Then I looked in to the Layout file under the Application model. It seemed to be using some thing different. And I updated it as follows.
public function viewContactAction(){
// Get the user id from url
$id = $this->params()->fromRoute('id');
//$this->headScript = new HeadScript();
$this->headScript()->appendFile('../../js/pages/lib/contact.view.js');
$this->headScript()->appendFile('../../js/packages/json-populate/dist/jquery.jsonPopulate.min.js');
$view = new ViewModel(array('title' => 'Contact View', 'contact_id' => $id));
$view->setTemplate('contacts/contacts/contact');
return $view;
//die("User View for $id");
}
Thinking it would be some thing like a file-not-found issue, I changed the file paths as if it was in the public folder /js/pages/lib/contact.view.js, but still the files don't show up.
Is using HeadScript in the controller no longer supported? Or has the way changed? Thanks in advance.
ok, this is my layout file. I don't remember making any changes to it except add some js.
<?php echo $this->doctype(); ?>
<html lang="en">
<head>
<meta charset="utf-8">
<?php echo $this->headTitle('ZF2 '. $this->translate('Skeleton Application'))->setSeparator(' - ')->setAutoEscape(false) ?>
<?php echo $this->headMeta()->appendName('viewport', 'width=device-width, initial-scale=1.0') ?>
<!-- Le styles -->
<?php echo $this->headLink(array('rel' => 'shortcut icon', 'type' => 'image/vnd.microsoft.icon', 'href' => $this->basePath() . '/images/favicon.ico'))
->prependStylesheet($this->basePath() . '/css/bootstrap-responsive.min.css')
->prependStylesheet($this->basePath() . '/css/style.css')
->prependStylesheet($this->basePath() . '/css/bootstrap.min.css') ?>
<!-- Scripts -->
<?php echo $this->headScript()->prependFile($this->basePath() . '/js/html5.js', 'text/javascript', array('conditional' => 'lt IE 9',))
->prependFile($this->basePath() . '/js/bootstrap.min.js')
->prependFile($this->basePath() . '/js/jquery.min.js')
->appendFile($this->basePath() . '/js/jquery.konnections.tableDefinition.js')
->appendFile($this->basePath() . '/js/jquery.konnections.appendTemplateFromJSON.js'); ?>
<?php //echo $this->headScript; ?>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="<?php echo $this->url('home') ?>"><?php echo $this->translate('Skeleton Application') ?></a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><?php echo $this->translate('Home') ?></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<?php echo $this->translate('Contacts'); ?>
</a>
<ul class="dropdown-menu">
<li><a href='contacts'>Contact Table</a></li>
<li><a href='contacts/add-contact'>Add New Contact</a></li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<?php echo $this->content; ?>
<hr>
<footer>
<p>© 2005 - 2012 by Zend Technologies Ltd. <?php echo $this->translate('All rights reserved.') ?></p>
</footer>
</div> <!-- /container -->
<?php echo $this->inlineScript() ?>
</body>
</html>
The Generated source looks like this (page is kinda very long, so only the header i sincluded).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ZF2 Skeleton Application</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Le styles -->
<link href="/css/bootstrap.min.css" media="screen" rel="stylesheet" type="text/css">
<link href="/css/style.css" media="screen" rel="stylesheet" type="text/css">
<link href="/css/bootstrap-responsive.min.css" media="screen" rel="stylesheet" type="text/css">
<link href="/images/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon">
<!-- Scripts -->
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript" src="/js/bootstrap.min.js"></script>
<!--[if lt IE 9]><script type="text/javascript" src="/js/html5.js"></script><![endif]-->
<script type="text/javascript" src="/js/jquery.konnections.tableDefinition.js"></script>
<script type="text/javascript" src="/js/jquery.konnections.appendTemplateFromJSON.js"></script> </head>
You're trying to use a ViewHelper at the ControllerLevel. This isn't possible like this. The shorthand-functions like $this->blubb() inside the Controller are called ControllerPlugins. You can get a list of all the ControllerPlugins right here at Zend\Mvc\Controller\Plugin\*.
When you want to access a ViewHelper at the Controller-Level you need to gain access to the ViewHelperManager. This is done via the ServiceManager in the following manner:
$vhm = $this->getServiceLocator()->get('viewhelpermanager');
$headScript = $vhm->get('headscript');
$headScript->appendFile(/** ... */);
Didn't test it as it wasn't ever needed but it should definitely be working. Let me know in case it doesn't work ;)
I modified the above script.
This is the verified working code.
$vhm = $this->getServiceLocator()->get('ViewHelperManager');
$headScript = $vhm->get('headscript');
$headScript->appendFile( $url );
Related
I'm trying to use the autocomplete jquery function to complete a field with one of two source values: ['pere', 'mele']. unfortunately it does not work.
default.ctp
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<!------ Include the above in your HEAD tag ---------->
<?php echo $this->Html->script(['single']) ?>
in view file
<?php echo $this->Form->create($societa); ?>
<fieldset>
<h1>Aggiungi Società</h1>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->control('nome_societa',['class'=>'form-control','required' => true]);?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->control('nome_societa_abbreviato',['class'=>'form-control','required' => true]);?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->control('sede',['class'=>'form-control','id'=>'naruto','required' => true]);?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->control('cap',['class'=>'form-control','required' => true]);?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->control('citta',['class'=>'form-control']);?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->control('pr',['class'=>'form-control']);?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->button(__('Salva'),['class'=>'btn btn-primary']);?>
</div>
</div>
</fieldset>
<?php echo $this->Form->end();?>
<?php echo $this->Html->link('Indietro', ['action'=>'index'], ['class'=>'btn btn-primary']) ?>
in js file single.js
$(document).ready(function(){
$("#naruto").autocomplete({
source:['pere','mele']
});
});
in console google chrome
A cookie associated with a cross-site resource at http://bootstrapcdn.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
add#:1 A cookie associated with a cross-site resource at http://forum.jquery.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
add#:1 A cookie associated with a cross-site resource at https://forum.jquery.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
add#:1 A cookie associated with a cross-site resource at http://jquery.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
unfortunately the file does not work even if the console does not give errors
OK so it works. Fixed the various Jquery UI calls. Resolved
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Responsive sidebar template with sliding effect and dropdown menu based on bootstrap 3">
<title>Calciotel</title>
<link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/bootswatch/4.3.1/litera/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<?php
echo $this->Html->css(['jquery-ui.theme.min','jquery-ui.min','prova']);
echo $this->Html->script(['bootstrap.min','jquery-3.4.1.min','jquery-ui.min','prova','single','popper.min.js']);
echo $this->Html->meta('icon');
echo $this->fetch('meta');
echo $this->fetch('css');
echo $this->fetch('script');
echo $this->Html->charset();
?>
I was viewing lot's of tutorials , moving from web-forms and .master vs MVC Master layout.
the issue i have is regarding the embedded global files vs individual pages own files.
(files= styles and scripts)
Side note in my views i have implemented a little naming convention/rule so that layouts-masters has a LO postfix,
so if my app named "SAdmin", then my layout(master)-chtml will be named :_SAdminLO.cshtml
and in my layout-master i have :
(for simplicity)just a main bar - links (so that all pages has the "links" top-bar)
this is the main layout
[textlink1] | [textlink2] | [textlink3] | [textlink4] ....
then i have index page(it's name is cpanel)
in my index cpanel.chtml i have added icons in addition to the main layout's textual bar ... replication of the top bar in a form of
icons menu
[IMG] [IMG]
page_name page_name
[IMG] [IMG]
page_name page_name
so together Layout-master _SAdminLO.cshtml + cpanel.chtml - froms the "home page" of my app
now i have individual pages that are totally independent in their actions
but all they need is the css + html of the top bar, as opposed to cpanel (the index)
so my situation is that:
in rightclick-> view-source, i can see that all my pages has double html tags -
<html> + <head> + <body> markup of `LO`
&
<html> + <head> + <body> markup of `individual.cshtml `
the files :
-master-
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href='#Href("~/Content/css/GlobUtils.css")' rel='stylesheet' type='text/css' />
<title>#ViewBag.Title</title>
#Scripts.Render("~/js")// C# bundle
#RenderSection("head", false)
</head>
<body id="bodid">
<h2>Cpanel</h2>
<div id="navbar">
<ul id="nav">
<div class="menu-main-container">
<ul id="menu-main" class="menu">
<li id="menu-item-0" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-0 current_page_item menu-item-0">
#Html.ActionLink("Cpanel", "Cpanel", "ControlPanel")
</li>
<li id="menu-item-1" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-1 current_page_item menu-item-1">
#Html.ActionLink("Templates Generator", "TemplateGenerator", "ControlPanel")
</li>
<li id="menu-item-2" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-2 current_page_item menu-item-2">
#Html.ActionLink("Content Editor", "ContentEditor", "ControlPanel")
</li>
<li id="menu-item-3" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-3 current_page_item menu-item-2">
#Html.ActionLink("Files Uploader", "FilesUploader", "ControlPanel")
</li>
<li id="menu-item-4" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-4 current_page_item menu-item-2">
#Html.ActionLink("Code Dev", "CodeDev", "ControlPanel")
</li>
</ul>
</div>
</ul>
</div>
#RenderBody()
</body>
</html>
someindividualpage.chtml
#{
Layout = "~/Views/Shared/_EvProAdminLO.cshtml";
}
#model MvcE.Models.IndexModel.CreatedTemplateJPacket
<!DOCTYPE html>
#{
ViewBag.Title = "TemplateGenerator";
}
<html>
<head>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Template Generator</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.0/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href='#Href("~/Content/css/Chrm_TemplateGenerator.css")' rel="stylesheet" type="text/css" />
</head>
<body id="bodid">
<div id="DivEditor">
<h1 id="ContH"> ControlPanel - TemplateGenerator</h1>
<div class="container-fluid">
<div>
<a class="btn btn-CtrlsTmplt" id="save" href="#">save</a>
<a class="btn btn-CtrlsTmplt" id="load" href="#">load</a>
<a class="btn btn-CtrlsTmplt" id="clear" href="#">clear</a>
<input type="text" id="scr1" class="input_Border_AndBGClear" />
</div>
<hr/>
#*----------------------------------localData-------------------------------------*#
<div id="localData">
<input id="DataValue_FormFileds" type="hidden" />
</div>
</div>
</div>
<div id="SaveNewTmpltWwrap">
</div>
<script src='#Href("~/Js/jspart2.js")' type="text/javascript"></script>
</body>
Maybe I'm not quite understanding but it seems you can use custom sections.
_Layout
<html>
<head>
<title>#ViewBag.Title</title>
#* common script, css *#
<script src="jquery.js"></script>
#* variable script, css *#
#RenderSection("customHead", required: false)
</head>
<body>
<!-- nav bar here -->
#RenderBody()
#RenderSection("footer", required: false)
</body>
</html>
SomePage.cshtml
#{
Layout = "~/Views/Shared/_EvProAdminLO.cshtml";
ViewBag.Title = "Some Page 1";
}
#section customHead {
<script src="page1.js"></script>
}
#* no <html>,<head>,<body> *#
#* inserted into RenderBody() *#
<div id="page1content">
...
</div>
Because the section declared required: false it will won't try to render anything unless the view contains that section.
You can change the section content per page.
SomePage2.cshtml
#{
Layout = "~/Views/Shared/_EvProAdminLO.cshtml";
ViewBag.Title = "Some Page 2";
}
#section customHead {
<script src="page2.js"></script>
}
#section footer {
<div>footer</div>
}
<div id="page2content">
</div>
Rather than multiple layouts -- you can also use Partial Views and Child Actions to do variable content rendering.
SomePage3.cshtml
#{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Some Page 3";
}
#Html.Partial("widget")
#{Html.RenderAction("UserInfo");}
Now much of the layout content is removed and it becomes content inclusion rather than defining everything with exclusion rules.
I find fewer layout pages and using partials is more maintainable and the pages easier to understand what will render by looking at just the view page.
I have tried everything I can think of, but my page loads weirdly. With no style or form, and for the life of me, I have no clue why! Here is my code below : and attached is a picture of the outcome I get when running the code.
My outcome when I run this code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery Mobile Demos</title>
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" href="css/themes/default/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="_assets/css/jqm-demos.css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700">
<script src="js/jquery.js"></script>
<script src="_assets/js/index.js"></script>
<script src="js/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" data-theme="a">
<link rel="stylesheet" href="css/themes/default/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="_assets/css/jqm-demos.css">
<div data-role="header">
<div class="ui-btn-active" data-role="navbar">
<ul>
<li>
Find Us
</li>
<li>
Call Us
</li>
<ul>
</div>
</div>
<div class="ui-content" data-role="main">
<ul data-filter="true" data-insert="true" data-role="listview">
<li>
Brussels
</li>
<li>
Dublin
</li>
<li>
Cape Town
</li>
</ul>
</div>
<div data-role="footer" style="text-align:centure;">
<button class="ui-btn ui-icon-plus ui-btn-icon-left">Click
Me</button>
</div>
</div>
</body>
</html>
It's a simple typo. The first <ul> in your header's navbar is not closed.
Somehow jquery-mobile dont like this and stops rendering with a error. You should see this error in your browsers dev tools.
If your references to jquery and jquery-mobile are correct. it should work if you close the <li> tag
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery Mobile Demos</title>
<link rel="shortcut icon" href="favicon.ico">
<!-- jQuery Mobile -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<link rel="stylesheet" href="_assets/css/jqm-demos.css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700">
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="_assets/js/index.js"></script>
<!-- jQuery Mobile -->
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<div data-role="page" data-theme="a">
<link rel="stylesheet" href="css/themes/default/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="_assets/css/jqm-demos.css">
<div data-role="header">
<div class="ui-btn-active" data-role="navbar">
<ul>
<li>
Find Us
</li>
<li>
Call Us
</li>
</ul>
</div>
</div>
<div class="ui-content" data-role="main">
<ul data-filter="true" data-insert="true" data-role="listview">
<li>
Brussels
</li>
<li>
Dublin
</li>
<li>
Cape Town
</li>
</ul>
</div>
<div data-role="footer" style="text-align:center;">
<button class="ui-btn ui-icon-plus ui-btn-icon-left">
Click Me
</button>
</div>
</div>
Beside that, you have others error in your code.
You should insert your personal javascript code <script src="_assets/js/index.js"></script> after jquery and jquery-mobile. If you do so, you're always sure, that all libraries are loaded before you use them in your "personal" javascript file.
There is no need to include the same CSS Files twice. like you did with
css/themes/default/jquery.mobile-1.4.5.min.css and _assets/css/jqm-demos.css
In Jquery-mobile, there is the possibility to include CSS and/or Javascript file inside of the data-role="page" container. But in this case it makes absolut no sense.
The class ui-btn-active is unnecessary inside of the navbar <div>. If you want to set a button of your navbar active, you have to include this class inside of the <li> tag
And you have a typo inside of your footer. centure
I'm developping a new application using ZF2. The problem is in my .phtml file. I have a <div> contains a data-action for a js files, but the problem is that when I click nothing happens.
I do not know what the problem is.
Here is my code:
<html>
<head>
<meta charset="UTF-8">
<?php
echo $this->headLink(array('rel' => 'shortcut icon', 'type' => 'image/vnd.microsoft.icon', 'href' => $this->basePath() . '/img/favicon.ico'))
//<!-- Theme CSS -->
->prependStylesheet('/css/font.css')
->prependStylesheet('/css/picedit.css')
->prependStylesheet('/dist/css/picedit.min.css')
->prependStylesheet($this->basePath() . '/frontend/css/picedit.min.css')
?>
</head>
<body>
<form name="testform" action="out.php" method="post" enctype="multipart/form-data">
<div class="picedit_action_btns active">
<div class="picedit_control ico-picedit-picture" data-action="load_image"> </div>
<div class="picedit_control ico-picedit-camera" data-action="camera_open"> </div>
<div class="center">or copy/paste image here</div>
</div>
</form>
<script src="<?php echo $this->basePath(); ?>/dist/js/picedit.js"></script>
<script src="<?php echo $this->basePath(); ?>/dist/js/picedit.min.js"> </script>
<script src="<?php echo $this->basePath(); ?>/dist/js/jquery.min.js"> </script>
<script src="<?php echo $this->basePath(); ?>http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('.picedit_box').picEdit({
imageUpdated: function (img) {},
formSubmitted: function () {},
redirectUrl: false,
defaultImage: false
});
});
</script>
</body>
</html>
Any help please ?? Thanks.
It is better to add scripts like this:
<?php
echo $this->headScript()->prependFile($this->basePath() . '/js/some_file.js')
->prependFile($this->basePath() . '/js/another_file.js');
It is very similar to how you added the stylesheets.
You can check official ZF2 documentation on this here.
Please try this and please come back if it still doesn't work after that.
Is there a way to just set the body in Zend Framework 2? In Zend Framework 1 I could do it this way
$this->getResponse()->setBody('Hello World')
I found a way to set content in Zend Framework 2 but this also overwrites the layout and that's not what I want.
Here is another way to do that....
ModuleName/src/ModuleName/Controller/IndexController.php
<?PHP
namespace ModuleName\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class IndexController extends AbstractActionController
{
protected $helloWorldTable;
public function indexAction()
{
return new ViewModel(array(
'foo' => 'Hello World From Zend Framework 2!',
));
}
}
ModuleName/view/ModuleName/index/index.phtml
<?PHP
$this->headTitle('Some Site...');
echo "$hello";
?>
Application/view/layout/layout.phtml
doctype(); ?>
<html lang="en">
<head>
<meta charset="utf-8">
<?php echo $this->headMeta()->appendName('viewport', 'width=device-width, initial-scale=1.0') ?>
<!-- Le styles -->
<?php echo $this->headLink(array('rel' => 'shortcut icon', 'type' => 'image/vnd.microsoft.icon', 'href' => $this->basePath() . '/images/favicon.ico')) ?>
<!-- Scripts -->
<?php echo $this->headScript()->prependFile($this->basePath() . '/js/html5.js', 'text/javascript', array('conditional' => 'lt IE 9',))
->prependFile($this->basePath() . '/js/bootstrap.min.js')
->prependFile($this->basePath() . '/js/jquery.min.js') ?>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="<?php echo $this->url('index') ?>"><?php echo $this->translate('Spamus') ?></a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><?php echo $this->translate('Home') ?></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<?php echo $this->content; ?>
<hr>
<footer>
<p>© 2012 - 2013 by YourSite <?php echo $this->translate('All rights reserved.') ?></p>
</footer>
</div> <!-- /container -->
<?php echo $this->inlineScript() ?>
</body>
</html>
Whatever you changed Response body in controller, when zf2 MvcEvent::EVENT_RENDER trigger, a new Response body will be rebuilt. So correct way is change Response body AFTER MvcEvent::EVENT_RENDER.
Add this to your controller:
$this->getServiceLocator()->get('Application')->getEventManager()->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER, function($event){
$event->getResponse()->setContent('foobar');
}, -10000);
I finally got the solution. To change the content in the layout, just type in controller's action
$this->layout()->content = 'foobar';