Zend_Form action and method - zend-framework

Zend_Form action and method shows by default <form action="" method="post">
... My wish is not like that... Just be written <form> .. Is that possible ??
How can I do ???

well you can simply do the following but there really is no reason to to this!
why would you want en empty form tag?
add this to your config to let the framework "know" your new helper
resources.view.helperPath.My_View_Helper = "My/View/Helper"
then in the file library/My/View/Helper.php create the class
class My_View_Helper_Form extends Zend_View_Helper_Form
{
/**
* Render HTML form without any attributes on the form-tag
*
* #param string $name Form name
* #param null|array $attribs HTML form attributes
* #param false|string $content Form content
* #return string
*/
public function form($name, $attribs = null, $content = false)
{
$info = $this->_getInfo($name, $content, $attribs);
extract($info);
if (!empty($id)) {
$id = ' id="' . $this->view->escape($id) . '"';
} else {
$id = '';
}
if (array_key_exists('id', $attribs) && empty($attribs['id'])) {
unset($attribs['id']);
}
$xhtml = '<form>';
if (false !== $content) {
$xhtml .= $content
. '</form>';
}
return $xhtml;
}
}
it will automatically be used when you have configured your view resource properly

Related

display form data in another view in Zend

I am new in Zend, my problem can be simple for you. I want to make a controller that displays form input data in another view. data are an email text and a text file uploaded. I created the index view and result view.
but i get nothing. when I replace the value of $email with text it works!! I can't find what is going wrong.
The controller also should display a sorted file by firstname
Id,Firstname,Lastname
5,John,Doe
6,Adam,Ant
7,Victor,Hugo
8,Britannie,Spears
this is my controller :
public function indexAction()
{
// initialzing of the customized form
$form = new Application_Form_Upload();
$rq = $this->getRequest();
$isForm = true; // the form has to be shown only if true
if ($rq->isPost()) {
if ($form->isValid($rq->getPost())) {
// show the uploaded data instead of the form
$isForm = false;
$this->view->data = new Application_Model_DataViewer();
$this->view->data->parseFromForm($form);
$result = new Zend_View();
$this->view->result= $result;
$this->render('result');
}
}
if ($isForm) {
$this->view->form = $form;}
}
this is my model :
class Application_Model_DataViewer
{
/**
* #var string Entered e-mail address
*/
private $email;
/**
* #var array Array of extracted data from uploaded file
*/
private $data;
public function __construct(){
$this->email=null;
$this->data=array();
}
/**
* Extracts the data from the form-object and saves it internally
* #param $form Application_Form_Upload
*/
public function parseFromForm($form){
if(!isset($form))return;
if(!isset($form->file)||!$form->file instanceof Zend_Form_Element_File){
throw new Zend_Exception('The field File is empty or has wrong type');
}
// for validation of the IDs
$ival = new Zend_Validate_Int();
// reading the CSV-file (values should be separated by comma, if not - should be extended)
if(($fp = #fopen($form->file->getFileName(), 'r')) !== false){
while(($data = fgetcsv($fp, 500, ',')) !== false){
if(
!is_array($data)
||!$ival->isValid($data[0])
||count($data)<3
)continue;
$this->data[$data[1]] = $data;
}
}else{return;}
#fclose($fp);
ksort($this->data);
$this->email = $form->getValue('email');
}
/**
* #return null|string
*/
public function getEmail(){
return $this->email;
}
/**
* #return array
*/
public function getData(){
return $this->data;
}
}
and here is my index and result views
<?php
// the form should only be rendered if form must be shown
if(isset($this->form)){
$this->form->setAction($this->url());
echo $this->form;
}
?>
result view:
<?php
// if the required data is submitted, it will be checked and displayed
if(isset($this->data)){
?>
<p>Thank you <strong><?php echo $this->escape($this->data->getEmail()); ?></strong>.</p>
<p>The result of the sorting is:
<?php
foreach($this->data->getData() as $row){
echo '<div>', $this->escape($row[0]), ',',
$this->escape($row[1]), ',',
$this->escape($row[2]), '</div>';
}
?></p><?php
}
?>
Use the partial helper in the view.
See: http://framework.zend.com/manual/2.2/en/modules/zend.view.helpers.partial.html
eg. your index.phtml
if ($this->data) {
echo $this->partial("result.phtml", array("data" => $this->data->getData()));
}
you can access the variable in result.phtml by $this->data

zend: parameter collision

I wonder why no one ever asked this question.
Every zend Action function in controller class has 3 paramters, namely 'module', 'controller', and 'action'.
What happens, when I get a parameter named 'action' from a form or url, for example "?action=edit" ??
I tested it: action holds its value from router, not 'edit'.
public function someAction() {
$params = $this->getRequest()->getParams();
...
How could I pass the parameter named "action", if I had to ??
Thanks in advance.
The default route is Zend_Controller_Router_Route_Module which uses default keys for module, controller, & action:
protected $_moduleKey = 'module';
protected $_controllerKey = 'controller';
protected $_actionKey = 'action';
// ...
/**
* Set request keys based on values in request object
*
* #return void
*/
protected function _setRequestKeys()
{
if (null !== $this->_request) {
$this->_moduleKey = $this->_request->getModuleKey();
$this->_controllerKey = $this->_request->getControllerKey();
$this->_actionKey = $this->_request->getActionKey();
}
if (null !== $this->_dispatcher) {
$this->_defaults += array(
$this->_controllerKey => $this->_dispatcher->getDefaultControllerName(),
$this->_actionKey => $this->_dispatcher->getDefaultAction(),
$this->_moduleKey => $this->_dispatcher->getDefaultModule()
);
}
$this->_keysSet = true;
}
/**
* Matches a user submitted path. Assigns and returns an array of variables
* on a successful match.
*
* If a request object is registered, it uses its setModuleName(),
* setControllerName(), and setActionName() accessors to set those values.
* Always returns the values as an array.
*
* #param string $path Path used to match against this routing map
* #return array An array of assigned values or a false on a mismatch
*/
public function match($path, $partial = false)
{
$this->_setRequestKeys();
$values = array();
$params = array();
if (!$partial) {
$path = trim($path, self::URI_DELIMITER);
} else {
$matchedPath = $path;
}
if ($path != '') {
$path = explode(self::URI_DELIMITER, $path);
if ($this->_dispatcher && $this->_dispatcher->isValidModule($path[0])) {
$values[$this->_moduleKey] = array_shift($path);
$this->_moduleValid = true;
}
if (count($path) && !empty($path[0])) {
$values[$this->_controllerKey] = array_shift($path);
}
if (count($path) && !empty($path[0])) {
$values[$this->_actionKey] = array_shift($path);
}
if ($numSegs = count($path)) {
for ($i = 0; $i < $numSegs; $i = $i + 2) {
$key = urldecode($path[$i]);
$val = isset($path[$i + 1]) ? urldecode($path[$i + 1]) : null;
$params[$key] = (isset($params[$key]) ? (array_merge((array) $params[$key], array($val))): $val);
}
}
}
if ($partial) {
$this->setMatchedPath($matchedPath);
}
$this->_values = $values + $params;
return $this->_values + $this->_defaults;
}
You can see that the default module route has default keys for mvc params, however, it will use the keys set by the request object if it exists and we can modify these keys.
e.g. in your bootstrap:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initRequestKeys()
{
$this->bootstrap('frontcontroller');
$frontController = $this->getResource('frontcontroller');
/* #var $frontController Zend_Controller_Front */
$request = new Zend_Controller_Request_Http();
// change action key
$request->setActionKey("new_action_key");
// change module
$request->setModuleKey("new_module_key");
// change controller
$request->setControllerKey("new_controller_key");
// don't forget to set the configured request
// object to the front controller
$frontController->setRequest($request);
}
}
Now you can use module, controller, & action as $_GET params.
After a little testing it seems that how you pass the key "action" matters.
If you try and pass a parameter named "action" with $this->_request->getParams() you will get the controller action value key pair.
If you pass the "action" key from a form with $form->getValues() you will retrieve the value from the form element named "action".
As with so many things, your use case determines how you need to handle the situation.
Good Luck.

Zend Framework query db and getParam

At the moment I have a page where I have retrieved information on a club by the id of that club. I now have a comments box where I want to retrieve the comments about that club, in the comments table I have the club_id and the parameter "club_id" is passed into this page. At the moment I am retrieving all of the comments from the table but I want just the comments for that club. A point in the right direction would be great!
Controller:
class ClubDescriptionController extends Zend_Controller_Action
{
public $auth = null;
public function init()
{
$this->auth=Zend_Auth::getInstance();
}
http://pastebin.com/m66Sg26x
protected function authoriseUser()
{
if (!$this->auth->hasIdentity()) {
$route = array('controller'=>'auth', 'action'=>'index');
$this->_helper->redirector->gotoRoute($route);
}
}
}
Model:
class Application_Model_DbTable_Comments extends Zend_Db_Table_Abstract
{
protected $_name = 'comments';
public function getComment($id) {
$id = (int) $id;
$row = $this->fetchRow('id = ' . $id);
if (!$row) {
throw new Exception("Count not find row $id");
}
return $row->toArray();
}
public function addComment($comment, $club_id) {
$data = array(
'comment' => $comment,
'club_id' => $club_id,
'comment_date' => new Zend_Db_Expr('NOW()'),
);
$this->insert($data);
}
public function deleteComment($id) {
$this->delete('id =' . (int) $id);
}
}
The view:
<div id="view-comments">
<?php foreach($this->comments as $comments) : ?>
<p id="individual-comment">
<?php echo $this->escape($comments->comment);?> -
<i><?php echo $this->escape($comments->comment_date);?></i>
</p>
<?php endforeach; ?>
</div>
I realise I am going to have to use the getComment(); function in my model and query it by the id but I'm getting confused on exactly how...
Thanks
It's been a while since I used Db_Table but I think you want to create a select object, which allows you to build a query that will select comments with the correct club_id:
$comments = new Application_Model_DbTable_Comments();
$select = $comments->select();
$select->where('club_id = ?', $id);
$this->view->comments = $comments->fetchAll($select);
you may want to order the comments by date, if so, you can do this by adding an order clause to the select:
$select->order('comment_date ASC');
take a look at the docs for Zend_Db_Table_Select, which has quite a few examples: http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.fetch-all
In your controller you are calling
$this->view->comments = $comments->fetchAll();
it should be
$this->view->comments = $comments->getComment($this->_request->getParam('club_id'));
where id variable will be fetched from url.
Here is the working controller:
public function indexAction() {
//authorisation
$this->authoriseUser();
//to get the paramter club_id to query for specific club information
$id = (int) $this->_request->getParam('club_id', 0);
//submit a comment
$form = new Application_Form_Comment();
$form->submit->setLabel('Comment');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$comment = new Application_Model_DbTable_Comments();
$comment->addComment($formData['comment'], $id);
} else {
$form->populate($formData);
}
}
//initialise table
$clubs = new Application_Model_DbTable_Clubs();
$clubs = $clubs->getClub($id);
$this->view->clubs = $clubs;
//to get the comments for the club
$comments = new Application_Model_DbTable_Comments();
$select = $comments->select();
$select->where('club_id = ?', $id);
$select->order('comment_date ASC');
$this->view->comments = $comments->fetchAll($select);
}

Where should I locate logic related to layout in Zend Framework?

I need to customize the attributes of my body tag. Where should I locate the logic? In a Base Controller, view Helper ?
This should be the layout
<?=$this->doctype() ?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
...
</head>
<body<?=$this->bodyAttrs?>> <!-- or <?=$this->bodyAttrs()?> -->
...
</body>
</html>
And this should be the variables declaration in controllers
class Applicant_HomeController extends Zend_Controller_Action
{
public function indexAction()
{
$this->idBody = "someId1";
$this->classesBody = array("wide","dark");
}
public function loginAction()
{
$this->idBody = "someId2";
$this->classesBody = array();
}
public function signUpAction()
{
$this->idBody = "someId3";
$this->classesBody = array("no-menu","narrow");
}
}
This is the function where the attributes are concatenated.
/**
* #param string $idBody id Attribute
* #param array $classesBody class Attribute (array of strings)
*/
protected function _makeBodyAttribs($idBody,$classesBody)
{
$id = isset($idBody)?' id="'.$idBody.'"':'';
$hasClasses = isset($classesBody)&&count($classesBody);
$class = $hasClasses?' class="'.implode(' ',$classesBody).'"':'';
return $id.$class;
}
I need the last glue code.
Got one better for ya:
<?php
class My_View_Helper_Attribs extends Zend_View_Helper_HtmlElement
{
public function attribs($attribs) {
if (!is_array($attribs)) {
return '';
}
//flatten the array for multiple values
$attribs = array_map(function($item) {
if (is_array($item) {
return implode(' ', $item)
}
return $item;
}, $attribs);
//the htmlelemnt has the build in function for the rest
return $this->_htmlAttribs($attribs)
}
}
in your controller:
public function indexAction()
{
//notice it is $this->view and not just $this
$this->view->bodyAttribs= array('id' => 'someId', 'class' => array("wide","dark"));
}
public function loginAction()
{
$this->view->bodyAttribs['id'] = "someId2";
$this->view->bodyAttribs['class'] = array();
}
in your view script:
<body <?= $this->attribs($this->bodyAtrribs) ?>>

Zend Framework: What shld i use to automatically render out messages if any from FlashMessenger

i wonder if many of my pages may use a FlashMessenger, whats the best way to automatically render out all messages say at the top of the page (like those here in SO, telling the user they got a badge etc)
I have this view helper:
<?php
class Zf_View_Helper_FlashMessenger extends Zend_View_Helper_Abstract
{
/**
* #var Zend_Controller_Action_Helper_FlashMessenger
*/
private $_flashMessenger = null;
/**
* Display Flash Messages.
*
* #param  string $key Message level for string messages
* #param  string $template Format string for message output
* #return string Flash messages formatted for output
*/
public function flashMessenger($key = 'success',
$template='<div id="flash-message" style="display:none"><p class="%s">%s</p></div>')
{
$flashMessenger = $this->_getFlashMessenger();
//get messages from previous requests
$messages = $flashMessenger->getMessages();
//add any messages from this request
if ($flashMessenger->hasCurrentMessages()) {
$messages = array_merge(
$messages,
$flashMessenger->getCurrentMessages()
);
//we don't need to display them twice.
$flashMessenger->clearCurrentMessages();
}
//initialise return string
$output ='';
//process messages
foreach ($messages as $message)
{
if (is_array($message)) {
list($key,$message) = each($message);
}
$output .= sprintf($template,$key,$message);
}
return $output;
}
/**
* Lazily fetches FlashMessenger Instance.
*
* #return Zend_Controller_Action_Helper_FlashMessenger
*/
public function _getFlashMessenger()
{
if (null === $this->_flashMessenger) {
$this->_flashMessenger =
Zend_Controller_Action_HelperBroker::getStaticHelper(
'FlashMessenger');
}
return $this->_flashMessenger;
}
}
In my controller I have this:
if($form->isValid($formData))
{
$Model = $this->getModel();
$id = $Model->add($formData);
$this->_helper->flashMessenger('The category has been inserted.');
$this->_helper->redirector('list');
}
So, in my view I just echo the helper:
<?php echo $this->flashMessenger(); ?>
You could use a preDispatch-Plugin to inject the content of the FlashMessenger into your view and output it in your layout template.