What is the proper way to do conditional formatting in a ZF2 MVC project? - layout

In a ZF2 project I am developing, I would like to create a shell around the echo $this->content; statement in layout.phtml that would allow conditional formatting of the main content area. Specifically, I want to put the content into a column that is 75% wide and include some “ornamental” elements in a column that is 25% wide for most of the pages. However, I want to change to a single column for pages that need more space. My project is a CMS in which each page has an attribute that can tell either the view or the controller whether the page should be normal or wide. I have considered a number of methods for achieving what I’m after.
My “conditional formatting in the layout view” might look like this:
// module/Application/view/layout/layout.phtml:
//...
if ($templateNormal) {
echo "<div class='col-md-9'>";
} else {
echo "<div class='col-md-12'>";
}
echo $this->content;
if ($templateNormal) {
echo "</div>";
echo "<div class='col-md-3'>";
//... ornamentation
echo "</div>";
} else {
echo "</div>";
}
//...
While the above-method could work, for pure MVC I don’t think there is supposed to be any decision-making going on in the layout view.
My “conditional formatting in partial views” could look like this:
// module/Application/view/layout/layout.phtml:
//...
echo $this->partial('partial/open-shell.phtml');
echo $this->content;
echo $this->partial('partial/close-shell.phtml');
//...
// module/Application/view/partial/open-shell.phtml:
if ($templateNormal) {
echo "<div class='col-md-9'>";
} else {
echo "<div class='col-md-12'>";
}
// module/Application/view/partial/close-shell.phtml:
if ($templateNormal) {
echo "</div>";
echo "<div class='col-md-3'>";
//... ornamentation
echo "</div>";
} else {
echo "</div>";
}
Here the decision-making is taken out of the layout view, but it is simply put into other views so it's still in the view package and still not pure MVC.
In my “conditional formatting in the controller” solution, a pair of html script strings are developed in a controller function, and then passed on to the view. It might look like this:
// module/Application/view/layout/layout.phtml:
//...
echo $this->open-shell-script';
echo $this->content;
echo $this->close-shell-script';
//...
// some controller function:
//...
if ($templateNormal) {
$open-shell-script = "<div class='col-md-9'>";
$close-shell-script = "</div>";
$close-shell-script = "<div class='col-md-3'>";
$close-shell-script .= //... ornamentation
$close-shell-script .= "</div>";
} else {
$open-shell-script = "<div class='col-md-12'>";
$close-shell-script = "</div>";
}
//...
In this method, the decision-making is done in the controller where I assume it should be, but it seems odd to be writing html there.
Any comments or suggestions?

create two layout and in init() method of Module.php decide which layout should use .
public function init(ModuleManager $moduleManager) {
$sharedEvents = $moduleManager->getEventManager()->getSharedManager();
$sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
// This event will only be fired when an ActionController under the MyModule namespace is dispatched.
$controller = $e->getTarget();
$controller->layout(" your chose layout ");
}
}

There are many ways to accomplish this. This is one method and the logic lives in the controller:
controller
public function yourSampleAction()
{
// assign variables as usual to this view model
$viewModel = new ViewModel(array(
//vars
);
// this will be the "wrapper" and can be single, double column or anything else.
$wrapperViewModel = new ViewModel();
$wrapperViewModel->addChild($viewModel, 'innerContent');
// use this line when you want one column
$wrapperViewModel->setTemplate('path/to/your/single-column-wrapper.phtml');
// when this line you want two columns
$wrapperViewModel->setTemplate('path/to/your/two-column-wrapper.phtml');
return $wrapperViewModel;
}
two-column-wrapper.phtml
<div class='col-md-9'>
<?php echo $innerConntent; ?>
</div>
<div class='col-md-3'>
<!--- something else in here? -->
</div>
single-column-wrapper.phtml
<div class='col-md-12'>
<?php echo $innerConntent; ?>
</div>

Instead of setting different templates, you can adjust the Bootstrap Twitter classes by making the necessary classes dependent on a layout variable. You can use the logic in your controllers action to pass variables directly to the layout (not the view) like so:
$this->layout()->setVariables
(
array
(
'layoutVar1' => 75,
'someColClass' => ($someSwitch ? 'col-md-9':'col-md-12' ),
'layoutVar1' => 75,
)
);
and then just access these variables in the Layout as you would variables sent to the View. You don't have to even prepend them with "layout", they won't clash.

Related

Display Barcode for each Item in view Codeigniter using zend barcode framework

I have to develop software for shop. i have list of product having their price and barcode digits. I want to show each and every items in product list html page along with barcode to take a print of barcode on stickers.
I googled about the zend barcode rendering and i tested also and found result ok with one barcode but here is my mai problem arise that i want to generate multiple barcode in foreach loop on my view->page.
I am very new to codeigniter please help.
My Controller 'Barcode.php'.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Barcode extends CI_Controller {
public function __construct(){
parent::__construct();
if($this->session->userdata('successful_logged_in')){
//load library
$this->load->library('zend');
//load in folder Zend
$this->zend->load('Zend/Barcode');
$this->load->model('common_model');
}
else{
redirect('login','refresh');
}
}
public function index(){
//Generate 13 digit random number to render barcode
$temp = rand(1111111111111,9999999999999);
$this->set_barcode($temp);
$table='item_master';
$order_by='name ASC';
$data['item_list']=$this->common_model->select_active_records($table,$order_by);
$this->load->view('home/header');
$this->load->view($this->router->fetch_class().'/records',$data);
$this->load->view('home/footer');
}
public function set_barcode($code){
//generate barcode
Zend_Barcode::render('code128', 'image', array('text'=>$code), array());
}
In my View 'records.php'.
<tbody>';
$i=1;
if($item_list==false){
echo '<tr class="text-danger"><td colspan="3"><strong<i class="fa fa-info-circle" style="font-size:12pt;"></i> - No record found</td></tr>';
}
else{
foreach ($item_list as $row){
echo '<tr>';
echo '<td>'.$i++.'</td>';
echo '<td>'.$row->name.'</td>';
echo '<td>'.$row->price.'</td>';
echo '<td>'.$row->barcode.'</td>';
echo '</tr>';
}
}
echo'
</tbody>
But this shows me only one barcode on entire html body page which was generated by random number
I Want the final result something like this
Expected Result
// Create a folder in your root directory like : root/barcode
public function set_barcode($code){
//generate barcode
$file = Zend_Barcode::render('code128', 'image', array('text'=>$code), array());
$code = time().'1222';
imagepng($file,"barcode/{$code}.png");
$data['barcode'] = $code.'.png';
$this->load->view('dashboard/products',$data);
}
// Add view page like this
<img src="<?php echo base_url().'barcode/'.$barcode; ?>" alt="">

Yii 2 dropdown value safe newbie

I heard building Data in View is not very good, but anyway, i am wondering why its not working:
View
<?php $form = ActiveForm::begin();
$alleSpieler = \common\models\Spieler::find()->all();
if ($alleSpieler) {
unset($types);
foreach ($alleSpieler as $value) {
$types[$value->id] = $value->email . ' ' . $value->vorname . ' ' . $value->nachname;
}
}
echo $form->field($model, 'spielerId')->dropDownList($types, 'prompt'=>'Spieler manuell hinzufügen']);
ActiveForm::end();
?>
<?= AnmeldungDurchfuehrung2::widget(['durchfuehrungId' => $model->id, 'spielerId' => $model->spielerId]) ?>
Model
public $spielerId;
But spielerId ist not set in my Case. If i, for example, set 'spielerId' => 1120 in the widget call, it is working. But if i want the value from the dropdownlist, the action is saying that spielerId is missing. I am newbie and perhaps i forgot something? Thank you!
You must add $spielerId; in validation array in your model, som like this:
public function rules()
{
return [
[['spielerId'], 'integer'], //type of atribute value
[['spielerId'], 'required'], //if need
/*... other atributes ...*/
];
}
for more detail check the documentation.
okay now i know what i need:
echo $form->field($model, 'spielerId')->dropDownList($types,['prompt'=>'Waehlen Sie einen Spieler']);
echo Html::submitButton('Auswählen', ['class' => 'btn btn-primary']);
This is my Dropdown.
I need something like:
<?php if(!empty($_GET['spielerId'])) {
echo AnmeldungDurchfuehrung2::widget(['durchfuehrungId' => $model->id, 'spielerId' => $_GET['subject']]); }?>

Prevent CakePHP from stripping chars from url passed as param?

I am developing an application using CakePHP 2.6 and having issues with passing a string containing url characters as a parameter through to a controller method.
In my view I have a chunk of code which echoes out a series of table rows containing data and passes through the page id, unit id and the id of the link which can sometimes contain a url.
<?php foreach($linklist as $l) { ?>
<tr id="Link_<?php echo $l['ID']; ?>">
<td><?php echo $l['Title']; ?></td>
<td class="buttontd"><?php echo $this->Form->postlink('Delete', array('action' => 'deletelink', $this->request->params['pass'][0], $results[0]['PageUnitTypeID'], $l['ID']), array('class' => 'button delete')); ?></td>
</tr>
<?php } ?>
When the postlink button passes the information over to the 'deletelink' action in the controller the url looks like this:
http://mydomainname.com/webpages/deletelink/239/7/urlhttp%3A%2F%2Fwww.google.co.uk%2F
Which shows that the url has been passed as the string but then in the action when I try to just var_dump() the third parameter it returns a string of www.google.co.uk and nothing more which is preventing me from doing a substr() call on the parameter to check if the first 3 characters are equal to url or not.
I have tried to wrap the parameter in the postlink call inside serialize() and urlencode() but neither has had the desired effect of returning the full string as
urlhttp%3A%2F%2Fwww.google.co.uk%2F
Does anyone know of a successful way to pass through a parameter like this without losing important characters?
Update 1: Deletelink action
public function deletelink($pid = null, $uid = null, $lid = null) {
$this->autoRender = false;
if (!is_null($pid) && is_numeric($pid) && !is_null($uid) && is_numeric($uid)) {
if (!is_null($lid)) {
if (substr($lid, 0, 3) == 'url') {
echo substr($lid, 0, 3);
} else {
echo substr($lid, 0, 3);
}
} else {
$this->Session->setFlash('It is unknown which link you wish to delete from the webpage', 'flash_message_bar', array('class' => 'error'));
return $this->redirect(array('action' => 'edit', $pid));
}
} else {
$this->Session->setFlash('It is unknown which on which webpage you wish to delete a link', 'flash_message_bar', array('class' => 'error'));
return $this->redirect(array('action' => 'index'));
}
}
CakePHP (or mod_rewrite I would say) is getting confused with the way your URL is formed.
Your safest option is to base64_encode the url parameter in the view, which will result in call similar to:
http://mydomainname.com/webpages/deletelink/239/7/dXJsaHR0cDovL3d3dy5nb29nbGUuY28udWsv
and base64_decode it later in the action, which will transform
dXJsaHR0cDovL3d3dy5nb29nbGUuY28udWsv
into
urlhttp://www.google.co.uk/

disable layout for particular pages in ZF2

How to disable particular layout(example:menus.phtml) for particular pages in controller in ZF2?? In the below example menus.phtml should be disable for specific pages. Remaining pages must contain menus.phtml like header and footer.
<div>
header.phtml
</div>
<div>
menus.phtml
</div>
<div>
<?php echo $this->content; ?>
</div>
<div>
footer.phtml
</div>
There are various aproaches to this. Also modules.zendframework has quite a few modules here that may help you out.
If you are still keen on writing that yourself you could add variables to your layout within your controllers like so:
<?php
//YourController.php
public function someAction()
{
...
$this->layout()->footer = 'default';
...
}
//layout.phtml
<?php if ($this->footer === 'default') : ?>
//show the footer
<?php endif; ?>
Doing this is pretty inefficient though. Just imagine you'd need to do this to every action in all the controllers... I sure would not like to do that.
Now zf2 has a service and event layer that could help us out quite a bit here. This is a pretty nice read and introduction to it. You'd just write a service and trigger a event on your controllers/routes/whatever. Now you would also probably like to configure what is shown and what is hidden right? Thats pretty easy, too. Just write yourself a config file and merge it with the global.config like so:
<?php
//CustomModule/module.php
public function getConfig() {
$config = array();
$configFiles = array(
include __DIR__ . '/config/module.config.php',
include __DIR__ . '/config/module.customconfig.php',
);
foreach ($configFiles as $file) {
$config = \Zend\Stdlib\ArrayUtils::merge($config, $file);
}
return $config;
}
Source: Where to put custom settings in Zend Framework 2?
First, get the controller or action name:
$controllerName =$this->params('controller');
$actionName = $this->params('action');
then in your layout/view script add a simple logic.
<?php if ($actionName != 'action that you want to disable the layout/menu'): ?>
echo $this->render('menus.phtml');
<?php endif; ?>

Cakephp Pagination with left right div combination

I am working in a cakephp 2+ project. I am implementing pagination for sorting product listing in two left and right div combination. I am able to make left div but could not make right one since offset can not be set in pagination. I need half items in left div and half items in right div, so I can set limit but not able to offset. How can i do this?
Controller code
public function index()
{
$rows=$this->Product->find('count', array('conditions'=>array('Product.allow'=>1)));
if($rows%2==0)
{
$this->paginate = array('conditions' => array('Product.allow'=>1,'limit'=>($rows/2));
$list_l = $this->paginate('Product');
$this->set('left_list',$list_l);
$this->paginate = array('conditions' => array('Product.allow'=>1,'limit'=>($rows/2), 'offset'=>$rows/2));
$list_r = $this->paginate('Product');
$this->set('right_list',$list_r);
}
else
{
$right_list=$this->Paginate('Product', array('Product.allow'=>1),array('limit'=>($rows-round($rows/2)), 'offset'=>round($rows/2)));
}
}
View Code
Foreach loop with array returned from controller
Why not call $this->paginate() once and loop over all the items and perform the split in the View itself? Performing both calls is rather wasteful of database resources.
In that case you would have have a call to $this->paginate in the Controller. Say you want five items in the left column and five in the right:
$products = $this->paginate = array('conditions' => array('Product.allow'=>1, 'limit' => 10));
$this->set('products', $products);
In the view:
<div class="left-column">
<?php
foreach ($products as $product) {
debug($product);
if ($count === 5) {
echo "</div>\n<div class=\"right-column\">";
$count = 1;
}
$count++;
}
?>
</div>
Another way would be to use array_chunk in the Controller. Using this core PHP function you'll end up with multidimensional numerically indexed array which you can loop over and wrap the child arrays in their relevant divs.
<?php
$limit = round(count($products)/2);
$products = array_chunk($products, $limit);
foreach ($products as $index=>$groupedProducts) {
echo ($index === 0) ? '<div class="left-column">': '<div class="right-column">';
foreach ($groupedProducts as $product) {
debug($product);
}
echo '</div>';
}
?>

Resources