zend paginator make other links and Action Calling concatinating with the URL - zend-framework

I am NEW to ZF .i used zend paginator in my first project .its working fine that is switching b/w pages with right result but the problem is that i have other links too in that view have a look to my view
<?php include "header.phtml"; ?>
<h1><?php echo $this->escape($this->title);?></h1>
<h2><?php echo $this->escape($this->description);?></h2>
Register
<table border="1" align="center">
<tr>
<th>User Name</th>
<th>First Name</th>
<th>Last Name</th>
<th>Action</th>
</tr>
<?php
foreach($this->paginator as $record){?>
<tr>
<td><?php echo $record->user_name;?></td>
<td><?php echo $record->first_name;?></td>
<td><?php echo $record->last_name;?></td>
<td>
Edit
|
Delete
</td>
</tr>
<?php } ?>
</table>
<?php echo $this->paginationControl($this->paginator, 'Sliding', 'pagination.phtml'); ?>
<?php include "footer.phtml"; ?>
as i said the pagination renders and working fine but when i click on these links
<a id="edit_link" href="edit/id/<?php echo $record->id;?>">Edit</a>
or
<a id="delete_link" href="del/id/<?php echo $record->id;?>">Delete</a>
or
Register
it is not calling the required action instead it make my url like this
(initial link) http://localhost/zend_login/web_root/index.php/task/list
after clicking any of the above link its like this
http://localhost/zend_login/web_root/index.php/task/list/page/edit/id/8
http://localhost/zend_login/web_root/index.php/task/list/page/edit/id/edit/id/23
http://localhost/zend_login/web_root/index.php/task/list/page/edit/id/edit/id/register http://localhost/zend_login/web_root/index.php/task/list/page/edit/id/edit/id/del/id/12
note its not happening when the page renders first time but when i click on any pagination link its doing so initialy its going to the reguired action and displaying a view...any help HERE IS THE ACTION
public function listAction(){
$registry = Zend_Registry::getInstance();
$DB = $registry['DB'];
$sql = "SELECT * FROM task ORDER BY task_name ASC";
$result = $DB->fetchAll($sql);
$page=$this->_getParam('page',1);
$paginator = Zend_Paginator::factory($result);
$paginator->setItemCountPerPage(3);
$paginator->setCurrentPageNumber($page);
$this->view->assign('title','Task List');
$this->view->assign('description','Below, are the Task:');
$this->view->paginator=$paginator;
}

Try:
// controller
$this->view->controllerName = $this->getRequest()->getControllerName();
// view script
Edit
|
Delete
or
Edit
|
Delete
Second example uses baseUrl() view helper that's using front controller's baseUrl setting. If you don't set baseUrl in your frontController it's trying to guess. As you're not using bootstrap functionality to set baseUrl you may do the following in index.php (not required):
$frontController = Zend_Controller_Front::getInstance();
$frontController->setBaseUrl('/');
Third possibility using url() view helper:
<a href="<?php echo $this->url(array(
'controller' => $controllerName,
'action' => 'edit',
'id' => $record_->id
)); ?>">Edit</a>
|
<a href="<?php echo $this->url(array(
'controller' => $controllerName,
'action' => 'del',
'id' => $record_->id
));?>">Delete</a>

add this in your action
$request = $this->getRequest();
$this->view->assign('url', $request->getBaseURL());
and replace your links in view with this
Add a Task
Edit
Delete

Related

Is it possible to profile Zend_Table queries?

I'm looking for a way to profile queries which are performed internally by Zend_Table.
For example, after you finish Quickstart course, how to profile all the queries that are performed ?
I've tried to enable profiler from application.ini like this:
resources.db.profiler.class = "Zend_Db_Profiler_Firebug"
resources.db.profiler.enabled = true
And placed next rows in a Guestbook controller:
...
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$profiler = $db->getProfiler();
echo $profiler->getTotalElapsedSecs();
Which gives me 0
I've also tried to enable profiler in a Bootstrap file like this:
protected function _initProfiler() {
$this->bootstrap("db");
$profiler = new Zend_Db_Profiler_Firebug("All DB Queries");
$profiler->setEnabled(true);
Zend_Registry::get("db")->setProfiler($profiler);
}
Whick doesn't give me any result (I've installed and tested Firebug and FirePHP, using Zend_Log_Writer_Firebug())
I will appreciate any help. Thanks !
I've not tried the Firebug profiler. But I do use a html table to output profiler info at the bottom of each page that does a query.
enable profiler in application.ini
resources.db.params.profiler = true
render the profile results in the layout:
<?php
$this->addScriptPath(APPLICATION_PATH . '/views/scripts');
echo $this->render('profiler.phtml')
?>
profiler.phtml the view to render
<?php
// get the default db adapter
$adapter = Zend_Db_Table::getDefaultAdapter();
$profiler = $adapter->getProfiler();
if ($profiler->getEnabled() && $profiler->getTotalNumQueries() > 0) :
?>
<div style='text-align:center'>
<h2>Database Profiling Report</h2>
<p>Total queries executed: <?php echo $profiler->getTotalNumQueries() ?></p>
<p>Total elapsed time: <?php echo $profiler->getTotalElapsedSecs() ?></p>
</div>
<table class='spreadsheet' cellpadding='0' cellspacing='0' style='margin:10px auto'>
<thead>
<tr>
<th>#</th>
<th>Query</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<?php foreach ($profiler->getQueryProfiles() as $queryNumber => $query) : ?>
<tr>
<td>(<?php echo $queryNumber + 1 ?>)</td>
<td><?php echo $query->getQuery(); ?></td>
<td><?php echo $query->getElapsedSecs(); ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php endif ?>
I don't imagine that using the firebug profiler is much more difficult.
The problem was in the parameters instantiation. When I've entered
resources.db.params.profiler.class = "Zend_Db_Profiler_Firebug"
resources.db.params.profiler.enabled = true
instead of previous configuration, everything went fine.
Note .params section of the parameter lines

Zend form elements coming from a database

Currently I'm stuck writing a edit function for an order page using zend framework
Here is the situation:
One order consist of multiple items
Eg Order Number 1
Consists of Items
OrderListId OrderId title Sent dateSent trackingNumber
1 1 Book A 0 12/12/12 44444
2 1 Book B 1 10/01/12 51223
3 1 Book C 0 01/02/12 33353
and so on...
Please notes: the table are stored in a database
I need to have a page where the user can edit title, Sent, dateSent and trackingNumber fields.
How can I use zend form to populate these fields for edit. Since I want to have one page they can edit all these orderlist items. Rather then the user have to click back and forward to edit each order list item individually.
What's the best approach to this situation?
Thanks so much in advance!
I suggest using ZF Data Grid.
I had a problem similar to this awhile back and I came up with a solution where I just appended an update link to the end of the table row and populated a form for update while still displaying current information.
The following code samples were built before I knew what I was doing with ZF so they may be a little messy. I ended up with what amounts to single view that handles all of my CRUD operations.
**All css selectors removed for clarity
The display view:
<?php if (isset($this->leadtracks)): ?>
<form method="post" action="/admin/track/deletetrack">
<table>
<tr>
<th colspan="5"><?php $this->tableHeader() ?></th>
</tr>
<tr>
<th>Select</th>
<th>Shift</th>
<th>Days Off</th>
<th>Slots</th>
<th> </th>
</tr>
<tr>
<?php
//begin foreach loop using alternate syntax
foreach ($this->leadtracks as $lt):
?>
<td><input type="checkbox" name="trackid[]"
value="<?php
//trackid as value for checkbox
echo $lt->trackid
?>" style="width: 2px" /></td>
<td><?php
//find and display shift name
$lt->getShift();
?></td>
<td><?php $lt->getDays(); ?></td>
<td><?php echo $this->escape($lt['qty'])?></td>
<td><a href="<?php
//link to update action passing trackid and bidlocationid values
echo $this->url(array('module' => 'admin',
'controller' => 'track',
'action' => 'updatetrack',
'trackid' => $lt['trackid'],
'bidlocationid' => $lt['bidlocationid']))
?>">Update</a></td>
</tr>
<?php endforeach ?>
<tr>
<th colspan="5">
<input type="submit" name="submit" value="Delete Selected" />
</th>
</tr>
</table>
<?php endif; ?>
<!-- further code removed for brevity -->
</form>
The updateAction(), only one action for demonstration:
public function updatetrackAction() {
//get form set new label and assign to view
$form = new Admin_Form_Track();
$form->submit->setLabel('Update Track');
$form->addTrack->setLegend('Update A Track');
$this->view->form = $form;
try {
//check is post and is valid and get values from form
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();
$trackId = $data['trackid'];
//save update data to database
$update = new Model();
$update->update($trackId, $data);
//generate meesage
$this->_helper->flashMessenger->addMessage(Zend_Registry::get('config')
->messages->trackupdate->successful);
$this->getHelper('Redirector')->gotoSimple('addtrack');
} else {
//if form is not vaild populate form for resubmission
$form->populate($this->getRequest()->getPost());
}
} else {
//if form is not posted populate form with data from database
$trackId = $this->_getParam('trackid', 0);
if ($trackId > 0) {
$z = new Model();
$y = $z->getTrack($trackId)->toArray();
$form->populate($y);
}
}
} catch (Zend_Exception $e) {
$this->_helper->flashMessenger->addMessage($e->getMessage()->getTrace());
$this->_redirect($this->getRequest()->getRequestUri());
}
}
The addAction() and the deleteAction() are very similar and use the same view script called through the action() helper. The result is a page in which add, update and delete actions are performed from what the user perceives as one page(check box for multiple deletes and a link for update, every refresh displays current data). Although I do move the form from side to side as a sort of visual clue, though it really doesn't matter as all actions are available on each page.
the update view:
<div>
<h3><?php echo ucwords($this->escape(strtoupper($this->station) . ' - ' . $this->bidloc)); //page header ?></h3>
<?php echo $this->form //edit/add form ?>
</div>
<div>
<?php echo $this->action('displaytrack', 'track', 'admin') //display view ?>
</div>
I'm sure this can be done with the partial() view helper, without using the action() helper and I'm sure it can be done inline, I just haven't taken the time to figure out how to do it.
good Luck.

ZendFramework echo db values if first string = a?

I have this code at the moment to echo out all my database entries, I am wondering what it looks like in ZF to echo out the entries if the first value of the db entry is a.
Code:
<table>
<?php foreach($this->clubs as $clubs) : ?>
<tr>
<td><a href="<?php echo $this->url(array('controller' => 'club-description', 'action' => 'index', 'club_id' => $clubs->id));?>">
<?php echo $this->escape($clubs->club_name);?></a></td>
<td><?php echo $this->escape($clubs->rating);?></td>
</tr>
<?php endforeach; ?>
</table>
Thanks
Rik
So, based on your comment it sounds like you want to group the clubs by letter on the page. Assuming they are being ordered alphabetically in your database query, the simplest way to do this is to keep a variable which stores the first letter of the last club in the loop. Then, on each iteration, you compare the first letter of the current club with the first letter of the previous club. If they are different, you output a new heading.
With your code this would look something like this:
<?php
$previousLetter = false;
?>
<table>
<?php foreach($this->clubs as $clubs) : ?>
<?php
$firstLetter = substr($clubs->_club_name, 0, 1);
if ($firstLetter != $previousLetter) {
?>
<tr>
<td><?php echo $firstLetter; ?></td>
</tr>
<?php } ?>
<tr>
<td><a href="<?php echo $this->url(array('controller' => 'club-description', 'action' => 'index', 'club_id' => $clubs->id));?>">
<?php echo $this->escape($clubs->club_name);?></a></td>
<td><?php echo $this->escape($clubs->rating);?></td>
</tr>
<?php $previousLetter = $firstLetter; ?>
<?php endforeach; ?>
</table>

unable to render Zend_Form

i'm trying to render a login form using Zend_Form, i want it to be rendered calling www.site.com/login or www.site.com/account/login, but once i've done all the steps below and i try to call /login or /account/login from my browser i'm getting a HTTP 500 (Internal Server Error).. even if the rest of the site works perfectly. Please help me figure out where i'm wrong..
(note that I'm using Zend Framework 1.11)
(1) Create the model through ZF
zf create model FormLogin
(2) Edit the new created model in application/models/FormLogin.php
class Application_Model_FormLogin extends Zend_Form
{
public function __construct($options = null)
{
parent::__construct($options);
$this->setName('login');
$this->setMethod('post'); // GET O POST
$this->setAction('/account/login'); // form action=[..]
$email = new Zend_Form_Element_Text('email');
$email->setAttrib('size', 35);
$pswd = new Zend_Form_Element_Password('pswd');
$pswd->setAttrib('size', 35);
$submit = new Zend_Form_Element_Submit('submit'); // submit button
$this->setDecorators( array( array('ViewScript', array('viewScript' => '_form_login.phtml'))));
$this->addElements(array($email, $pswd, $submit));
}
}
(3) Add loginAction to the Account controller
class AccountController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
}
public function loginAction()
{
$form = new Application_Model_FormLogin();
$this->view->form = $form;
}
}
(4) Create the View at application/views/scripts/account/login.phtml
<?php echo $this->form; ?>
(5) Create the page application/views/scripts/_form_login.phtml called by setDecorators() at the point (2)
<form id="login" action="<?php echo $this->element->getAction(); ?>"
method="<?php echo $this->element->getMethod(); ?>">
<p>
E-mail Address<br />
<?php echo $this->element->email; ?>
</p>
<p>
Password<br />
<?php echo $this->element->pswd; ?>
</p>
<p>
<?php echo $this->element->submit; ?>
</p>
</form>
(6) And this is my Bootstrap.php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function _initRoutes()
{
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$route = new Zend_Controller_Router_Route_Static (
'login',
array('controller' => 'Account', 'action' => 'login')
);
$router->addRoute('login', $route);
$route = new Zend_Controller_Router_Route (
'games/asin/:asin/',
array('controller' => 'Games',
'action' => 'view',
'asin' => 'B000TG530M' // default value
)
);
$router->addRoute('game-asin-view', $route);
}
}
Change your class definition for Application_Model_FormLogin to the following:
<?php
class Application_Model_FormLogin extends Zend_Form
{
public function init()
{
$this->setName('login');
$this->setMethod('post'); // GET O POST
$this->setAction('/account/login'); // form action=[..]
$email = new Zend_Form_Element_Text('email');
$email->setAttrib('size', 35);
$pswd = new Zend_Form_Element_Password('pswd');
$pswd->setAttrib('size', 35);
$submit = new Zend_Form_Element_Submit('submit'); // submit button
$this->setDecorators( array( array('ViewScript', array('viewScript' => '_form_login.phtml'))));
$this->addElements(array($email, $pswd, $submit));
}
}
You should set your form up using the init() method rather than using __construct()
When you call parent::__construct($options); in the constructor for your Zend_Form, that ends up calling the form's init() method and then nothing after that is executed so your form initialization and element creation was never being called.
The 500 internal server was because you were calling parent::__construct() and your form had no init() method.
drew010 has a good point about setting up your form in init() rather then__construct().
I just spent hours fighting with the viewScript method and this is how I got it to work (so far).
$this->view->form = $form assigns to the view
then in your view you need to render the partial with something like <?php echo $this->render('_form_login.phtml')
if you use this method then you access your elements using <?php echo $this->form->email; ?>
Using this method I did not use the $this->setDecorators( array( array('ViewScript', array('viewScript' => '_form_login.phtml')))); line of code.
The proper way to do this uses the viewScript decorator, however I have not been able to make it work yet. I did find that using this decorator I had to access the elements using $this->element->elementname, but I could not find anyway to access the method or action. getMethod() and getAction() both returned errors.
[EDIT]
ok i got it to work:
Make your form as normal using init()
$form->setDecorators(array(
array('ViewScript', array('viewScript' => '_yourScript.phtml'))
)); I like to add this in the controller.
in your viewScript access the form object using $this->element instead of $this->form
assign your form to the view normally $this->view->form = $form
render the form normally <?php echo $this->form ?>
this is the example I got to work...finally
<form action="<?php echo $this->element->getAction() ?>"
method="<?php echo $this->element->getMethod() ?>">
<table>
<tr>
<td><?php echo $this->element->weekend->renderLabel() ?></td>
<td><?php echo $this->element->weekend->renderViewHelper() ?></td>
<td><?php echo $this->element->bidlocation->renderLabel() ?></td>
<td><?php echo $this->element->bidlocation->renderViewHelper() ?></td>
<td><?php echo $this->element->shift->renderLabel() ?></td>
<td><?php echo $this->element->shift->renderViewHelper() ?></td>
</tr>
<tr>
<td colspan="6"><?php echo $this->element->submit ?></td>
</tr>
</table>
</form>
I think my hoof-in-mouth is cured for the moment.

jquery ajax in Zend framework

i am new to ZF i want to create ajax link that will go to "task" controller and "ajax" action
do something like this
$registry = Zend_Registry::getInstance();
$DB = $registry['DB'];
$sql = "SELECT * FROM task ORDER BY task_name ASC";
$result = $DB->fetchAll($sql);
than put the result in this div
<div id="container">container</div>
this is my view where i am doing this
<?php echo $this->jQuery()->enable(); ?>
<?php echo $this->jQuery()->uiEnable(); ?>
<div id="container">container</div>
<?php
echo $this->ajaxLink("Bring All Task","task/ajax",array('update' => '#container'));
?>
i dont know the syntax how i will do this , retouch my code if i am wrong i searched alot but all in vain plz explain me thanking you all in anticipation also refer me some nice links of zendx_jquery tutorial
This should work:
class IndexController extends Zend_Controller_Action
{
/**
* Homepage - display result of ajaxRequest
*/
public function indexAction()
{
}
/**
* Print result of database query
*/
public function ajaxAction()
{
// disable rendering of view and layout
$this->_helper->layout()->disableLayout();
$registry = Zend_Registry::getInstance();
$db = $registry['DB'];
// get select object to build query
$select = $db->select();
$select->from('task')->order('task_name ASC');
// echo result or what ever..
$this->view->tasks = $db->fetchAll($select);
}
}
// index.phtml (view)
<?php
echo $this->jQuery()->enable();
echo $this->jQuery()->uiEnable();
// create link to ajaxAction
$url = $this->url(array(
'controller' => 'index',
'action' => 'ajax',
));
?>
<div id="container">container</div>
<?php
echo $this->ajaxLink(
"Bring All Task", $url, array('update' => '#container')
);
?>
and in your ajax.phtml
<?php if ($this->tasks): ?>
<table>
<tr>
<th>task ID</th>
<th>task Name</th>
</tr>
<?php foreach($this->tasks as $task) : ?>
<tr>
<td><?php echo $task['task_id']; /* depending on your column names */ ?>
</td>
<td><?php echo $this->escape($task['task_name']); /* to replace " with " and so on */ ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
No tasks in table.
<?php endif; ?>
regarding db you have to setup it first somewhere earlier in your code, for example front controller index.php or bootstrap.php, for example:
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => '127.0.0.1',
'username' => 'webuser',
'password' => 'xxxxxxxx',
'dbname' => 'test'
));
Zend_Registry::set('DB', $db);