ZF2 How to set search form in layout - forms

What is the right way to set a (search) form with Zend Framework 2 in the layout.ptml who is visible on any page of the website?
Thanks in advance.
Nick

It is really simple to set any variables to all layouts in ZF2 by EventManager, just attach the EVENT_RENDER event such as:
class Module
{
public function onBootstrap($e)
{
$app = $e->getParam('application');
$app->getEventManager()->attach(MvcEvent::EVENT_RENDER, array($this, 'setFormToView'), 100);
}
public function setFormToView($event)
{
$form = new MyForm();
$viewModel = $event->getViewModel();
$viewModel->setVariables(array(
'form' => $form,
));
}
}

For view in layout use:
<?php if ($user = $this->identity()): ?>
<?php echo 'Login with user' . $this->escapeHtml($user->nome); ?>
| <?php echo $this->translate('Sair'); ?>
<?php else: ?>
<?php
echo $this->form()->openTag($form);
echo "<h5>Forneça seu login e senha </h5>";
echo $this->formRow($form->get('username'));
echo $this->formRow($form->get('password'));
echo $this->formRow($form->get('rememberme'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
?>
<?php endif; ?>

Related

Codeigniter redirect to empty form

I have the follow form in Codeigniter:
The controller:
public function item($alias = NULL){
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Edit menu';
$data['menu_item'] = $this->menu_model->get_menu($alias);
$data['articole'] = $this->menu_model->get_articole();
$data['menuactive'] = $this->menu_model->get_menuactiv();
$data['errors'] = $this->form_validation->error_array();
$this->form_validation->set_rules('position','Position','required');
$this->form_validation->set_rules('position','Position','numeric');
$this->form_validation->set_rules('name','Name','required');
if ($this->form_validation->run() === FALSE) {
$data['name'] = $data['menu_item']['name'];
$this->load->view('templates/header', $data);
$this->load->view('templates/youarehere', $data);
$this->load->view('templates/menu', $data);
$this->load->view('templates/admin', $data);
$this->load->view('menu/item', $data);
$this->load->view('templates/footer');
}
else {
$this->menu_model->update_menu();
redirect('menu');
}
}
The item view is:
<?php echo validation_errors(); ?>
<?php echo form_open('menu/item'); ?>
<?php echo form_label('ID ', 'id'); ?>
<?php echo form_input('id', $menu_item['id'], 'readonly'); ?><br><br>
<?php echo form_label('Name ', 'name'); ?>
<?php echo form_input('name', $menu_item['name']); ?><br><br>
<?php echo form_label('Position ', 'position'); ?>
<?php echo form_input('position', $menu_item['position']); ?><br><br>
<?php foreach($articole as $articole_item):
$articol1[] = $articole_item['id'] . ' ' . $articole_item['title'];
endforeach; ?>
<?php echo form_label('Associated article ', 'associated_article'); ?>
<?php echo form_dropdown('associated_article', $articol1, $menu_item['articol_asociat']); ?><br><br>
<?php echo form_label('Menu activ ', 'activ'); ?>
<?php echo form_checkbox('activ', '1', TRUE); ?><br><br>
<input type="submit" name="submit" value="Save menu"/>
</form>
In this view I edited menu items. Everything works fine when when everything is right. When I introduce something wrong in a field, like string into "position" field, the form redirect to item view, but with empty fields and with the error message. I want to keep what is entered in field and the error message.
What is wrong with my code?
Change your form :
<?php echo form_label('ID ', 'id'); ?>
<?php echo form_input('id', set_value('id'), 'readonly'); ?><br><br>
<?php echo form_label('Name ', 'name'); ?>
<?php echo form_input('name', set_value('name')); ?><br><br>
<?php echo form_label('Position ', 'position'); ?>
<?php echo form_input('position', set_value('position')); ?>
set_value() replace your old values

how to, hidden field value not showing up on request in zend framework?

i have a simple form that has a textarea ans a hidden field
$textarea = new Zend_Form_Element_Textarea('post');
$textarea->setRequired(true);
$textarea->setLabel('');
$hidden = new Zend_Form_Element_Hidden('post_id');
$hidden->setLabel('');
$hidden->setValue('1');
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('test');
$this->addElement($textarea);
$this->addElement($hidden);
$this->addElement($submit);
$this->setDecorators(array(
'FormElements',
array('HtmlTag', array('tag' => 'div', 'class' => 'form_class')),
'Form'
));
in my view i do
<?php echo $this->form->getElement('post')->render(); ?>
<?php echo $this->form->getElement('submit')->render(); ?>
then in my controller
$request = $this->getRequest();
if( $request->isPost() && $form->isValid($request->getParams()))
{
Zend_Debug::dump($request->getParams());
}
what happens is that i get
array(8) {
["module"] => string(6) "testr"
["controller"] => string(8) "posts"
["action"] => string(9) "post"
["post"] => string(10) "testgfdgfg"
["submit"] => string(26) "submit"
}
but no post_id
this is a bit wired and i cant figure it out. Ive looked for any code that might screw this up but nothing. I've also tried to echo the hidden field in the view, but i still get nothing on the request
any ideas?
thanks
In your view do
<?php echo $this->form->getElement('post'); ?>
<?php echo $this->form->getElement('post_id'); ?>
<?php echo $this->form->getElement('submit');?>
You are simply not echoing post_id element like you did with post and submit . Also you don't need to call render() since php magic function __toString() proxy render() in all Zend_Form_Element_XXX .
In View part you are just set two elements only
<?php echo $this->form->getElement('post')->render(); ?>
<?php echo $this->form->getElement('submit')->render(); ?>
WHERE form->getElement('post_id')->render(); ?>
<?php echo $this->form->getElement('post')->render(); ?>
<?php echo $this->form->getElement('submit')->render(); ?>
<?php echo $this->form->getElement('post_id')->render(); ?>
Try once with this.
I think it will work.

Form with embedded relation won't save Symfony 1.4 Doctrine

I have embedded the Mutt form within the Mix form:
MixForm.class.php:
$this->embedRelation('Mutt');
$form = new MuttForm(null, array(
'mix' =>$this->getObject(),
));
$this->embedForm('Mutt', $form);
$this->widgetSchema['Mutt'] = $form->getWidgetSchema();
$this->widgetSchema['Mutt']['mix_id'] = new sfWidgetFormInputHidden();
$this->validatorSchema['Mutt'] = $form->getValidatorSchema();
I need the newly created id form for the Mix table to populate the mix_id field in the Mutt table.
<?php echo $form->renderHiddenFields();?>
<?php echo $form['name']->renderRow();?>
<?php echo $form['parent1']->renderRow();?>
<?php echo $form['parent2']->renderRow();?>
<?php echo $form['parent3']->renderRow();?>
<?php echo $form['parent4']->renderRow();?>
<?php echo $form['parent5']->renderRow();?>
<?php echo $form['Mutt']['creator']->renderRow();?>
<?php echo $form['Mutt']['email']->renderRow();?>
<?php echo $form['Mutt']['website']->renderRow();?>
<?php echo $form['Mutt']['caption']->renderRow();?>
<?php echo $form['Mutt']['photo']->renderRow();?>
<?php echo $form['Mutt']['copyright']->renderRow();?>
<?php echo $form['Mutt']->renderHiddenFields();?>
Here is my action in modules/mix/actions/actions.class.php
public function executeEdit(sfWebRequest $request)
{
$this->form = new MixForm();
if($request->isMethod('post')):
$this->form->bind($request->getParameter('mix'), $request->getFiles($this->form->getName()));
if($this->form->isValid()):
$this->form->save();
$this->redirect('pure/add');
endif;
endif;
}
The form validation works correctly, but it won't save in either database.
What am I doing wrong??
You are defining an action for executeEdit, but processForm is the action where form validation and saving to the database occur. executeEdit is the action for displaying a form when editing an existing job.
See: http://www.symfony-project.org/jobeet/1_4/Doctrine/en/10#chapter_10_sub_the_form_action

Type of Flash Messenger in Zend

Is it possible or How can i give a type to a FlashMessage in Zend?
For example
/* This is a "Success" message */
$this -> _helper -> FlashMessenger('You are successfully created a post.');
/* This is an "Error" message */
$this -> _helper -> FlashMessenger('There is an error while creating post.');
/* This is just a "Notification" message */
$this -> _helper -> FlashMessenger('Now you can see your Post');
I think the best way to do this is by using the flashmessenger namespaces:
/* success message */
$this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Post created!');
/* error message */
$this->_helper->FlashMessenger()->setNamespace('error')->addMessage('You have no permissions');
And then in your layout you can get the messages added to each namespace:
<?php $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
<?php if ($flashMessenger->setNamespace('success')->hasMessages()): ?>
<div class="message success">
<?php foreach ($flashMessenger->getMessages() as $msg): ?>
<?php echo $msg ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($flashMessenger->setNamespace('error')->hasMessages()): ?>
<div class="message error">
<?php foreach ($flashMessenger->getMessages() as $msg): ?>
<?php echo $msg ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
At one time you used assoc arrays to do this... Im not ure if this is still current or not...
/* This is a "Success" message */
$this -> _helper -> FlashMessenger(array('success' => 'You are successfully created a post.'));
/* This is an "Error" message */
$this -> _helper -> FlashMessenger(array('error' => 'There is an error while creating post.'));
/* This is just a "Notification" message */
$this -> _helper -> FlashMessenger(array('notice' => 'Now you can see your Post'));
It is possible. Sample implementation in described in this blog post:
Zend Framework: View Helper Priority Messenger | emanaton
Excerpt:
class AuthController extends Zend_Controller_Action {
function loginAction() {
. . .
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if ($this->view->form->isValid($formData)) {
. . .
} else {
$this->view->priorityMessenger('Login failed.', 'error');
}
. . .
}
}
Method signatures in Zend Framework 1.12.x for FlashMessenger:
public function addMessage($message, $namespace = null)
public function getMessages($namespace = null)
public function hasMessages($namespace = null)
public function clearMessages($namespace = null)
So to set messages the following will work:
/* success message */
$this->_helper->flashMessenger()->addMessage('Post created!', 'success');
/* error message */
$this->_helper->flashMessenger()->addMessage('You have no permissions', 'error');
And for the view, the following should work:
<?php $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
<?php if ($flashMessenger->hasMessages('success')): ?>
<div class="message success">
<?php foreach ($flashMessenger->getMessages('success') as $msg): ?>
<?php echo $msg ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($flashMessenger->hasMessages('error')): ?>
<div class="message error">
<?php foreach ($flashMessenger->getMessages('error') as $msg): ?>
<?php echo $msg ?>
<?php endforeach; ?>
</div>
<?php endif; ?>

zend framework components DB can't find class Zend_Paginator_Adapter_DbTableSelect

I'm using some Zend libraries outside of the Zend Framework in a small project.
I'm using Zend_Db and Zend_Paginator but when I'm trying to set up the pagination using Zend_Paginator_Adapter_DbTableSelect I get an error that it can't find the class.
Fatal error: Class 'Zend_Paginator_Adapter_DbTableSelect' not found in C:\xampp\htdocs\php_testing\zend\zend_db\index1.php on line 65
Here is my code:
<?
require_once 'Zend/Db.php';
$config=array(
'adapter' => 'PDO_MYSQL',
'hostname' => 'localhost',
'dbname' => 'dm_xxxx',
'username' => 'un',
'password' => 'pw'
);
$db=Zend_Db::factory($config['adapter'], $config);
$select=$db->select()
->from('photocontest__photos', array('*'))
->order('created')
;
require_once 'Zend/Paginator.php';
$currentPageNumber = ($_GET['page'] > 0)?$_GET['page']:'1';
$totalNumberOfItems = 11;
$itemsPerPage = 5;
$pageRange = 10;
$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
$paginator = new Zend_Paginator($adapter);
$paginator->setCurrentPageNumber($currentPageNumber);
$paginator->setItemCountPerPage($itemsPerPage);
$scrollType = 'Sliding';
$paginator = get_object_vars($paginator->getPages($scrollType));
foreach($paginator AS $item){
echo $item->title.'<br>';
}
?>
thanks
######### UPDATE EDIT ##########
<?
$config=array(
'adapter' => 'PDO_MYSQL',
'hostname' => 'localhost',
'dbname' => 'dm_xxxx',
'username' => 'un',
'password' => 'pw'
);
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();
$db=Zend_Db::factory($config['adapter'], $config);
$table = new Photos(array('db' => $db));
$select = $table->select();
$select->setIntegrityCheck(false)
->from('photocontest__photos', array('*'))
->order('created')
;
$currentPageNumber = ($_GET['page'] > 0)?$_GET['page']:'1';
$itemsPerPage = 6;
$adapter = new Zend_Paginator_Adapter_DbTableSelect($select); //Setup the adapter object
$paginator = new Zend_Paginator($adapter); //Setup the actual paginator object
$paginator->setCurrentPageNumber($currentPageNumber);
$paginator->setItemCountPerPage($itemsPerPage); // items pre page
$scrollType = 'Sliding'; //change this to 'All', 'Elastic', 'Sliding' or 'Jumping' to test all scrolling types
Zend_Paginator::setDefaultScrollingStyle('Sliding'); // Sliding or Elastic
//Zend_View_Helper_PaginationControl::setDefaultViewPartial('pagination.phtml');
$paginatorControl = get_object_vars($paginator->getPages($scrollType)); //and that's it! we can now use the $paginator variable as we want
?>
<h1>Zend_Paginator Demo</h1>
<ul id="items">
<?php foreach($paginator AS $item): ?>
<li><?php echo $item->title; ?></li>
<?php endforeach ?>
</ul>
<div id="paginator">
<p>Showing <strong><?php echo $paginatorControl['firstItemNumber'] ?> to <?php echo $paginatorControl['lastItemNumber'] ?></strong> out of <strong><?php echo $paginatorControl['totalItemCount'] ?></strong> items</p>
<?php if($paginatorControl['previous']): ?>
« Prev
<?php else: ?>
<span>« Prev</span>
<?php endif ?>
<?php if($paginatorControl['firstPageInRange'] > $paginatorControl['first']): ?>
<?php echo $paginatorControl['first'] ?>
<span>...</span>
<?php endif ?>
<?php foreach($paginatorControl['pagesInRange'] as $page): ?>
<?php if($page == $paginatorControl['current']): ?>
<span><?php echo $page ?></span>
<?php else: ?>
<?php echo $page ?>
<?php endif ?>
<?php endforeach ?>
<?php if($paginatorControl['lastPageInRange'] < $paginatorControl['last']): ?>
<span>...</span>
<?php echo $paginatorControl['last'] ?>
<?php endif ?>
<?php if($paginatorControl['next']): ?>
Next »
<?php else: ?>
<span>Next »</span>
<?php endif ?>
</div>
Edited: I dont think my frirst solution will help you unless you can live without Zend_Paginator_Adapter_DbTableSelect. But looking at your code have you tried including directely DbTableSelect.php?
Try using ::factory.
$paginator = Zend_Paginator::factory($adapter);
$paginator->setCurrentPageNumber($currentPageNumber);
$paginator->setItemCountPerPage($itemsPerPage);
$scrollType = 'Sliding';
$paginator = get_object_vars($paginator->getPages($scrollType));
<?
$config=array(
'adapter' => 'PDO_MYSQL',
'hostname' => 'localhost',
'dbname' => 'dm_xxxx',
'username' => 'un',
'password' => 'pw'
);
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();
$db=Zend_Db::factory($config['adapter'], $config);
$table = new Photos(array('db' => $db));
$select = $table->select();
$select->setIntegrityCheck(false)
->from('photocontest__photos', array('*'))
->order('created')
;
$currentPageNumber = ($_GET['page'] > 0)?$_GET['page']:'1';
$itemsPerPage = 6;
$adapter = new Zend_Paginator_Adapter_DbTableSelect($select); //Setup the adapter object
$paginator = new Zend_Paginator($adapter); //Setup the actual paginator object
$paginator->setCurrentPageNumber($currentPageNumber);
$paginator->setItemCountPerPage($itemsPerPage); // items pre page
$scrollType = 'Sliding'; //change this to 'All', 'Elastic', 'Sliding' or 'Jumping' to test all scrolling types
Zend_Paginator::setDefaultScrollingStyle('Sliding'); // Sliding or Elastic
//Zend_View_Helper_PaginationControl::setDefaultViewPartial('pagination.phtml');
$paginatorControl = get_object_vars($paginator->getPages($scrollType)); //and that's it! we can now use the $paginator variable as we want
?>
<h1>Zend_Paginator Demo</h1>
<ul id="items">
<?php foreach($paginator AS $item): ?>
<li><?php echo $item->title; ?></li>
<?php endforeach ?>
</ul>
<div id="paginator">
<p>Showing <strong><?php echo $paginatorControl['firstItemNumber'] ?> to <?php echo $paginatorControl['lastItemNumber'] ?></strong> out of <strong><?php echo $paginatorControl['totalItemCount'] ?></strong> items</p>
<?php if($paginatorControl['previous']): ?>
« Prev
<?php else: ?>
<span>« Prev</span>
<?php endif ?>
<?php if($paginatorControl['firstPageInRange'] > $paginatorControl['first']): ?>
<?php echo $paginatorControl['first'] ?>
<span>...</span>
<?php endif ?>
<?php foreach($paginatorControl['pagesInRange'] as $page): ?>
<?php if($page == $paginatorControl['current']): ?>
<span><?php echo $page ?></span>
<?php else: ?>
<?php echo $page ?>
<?php endif ?>
<?php endforeach ?>
<?php if($paginatorControl['lastPageInRange'] < $paginatorControl['last']): ?>
<span>...</span>
<?php echo $paginatorControl['last'] ?>
<?php endif ?>
<?php if($paginatorControl['next']): ?>
Next »
<?php else: ?>
<span>Next »</span>
<?php endif ?>
</div>