jquery ajax in Zend framework - 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);

Related

Yii 2 Call to a member function saveAs() on string

new to Yii and I am getting this error on a Send Email page. The string in question is the path to the attachment and the attachment name and i am presuming that the saveAs function would expect a string. Any ideas what i am missing?
The form:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\emails */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="emails-form">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'reciever_name')->textInput(['maxlength' => 50]) ?>
<?= $form->field($model, 'receiver_email')->textInput(['maxlength' => 200]) ?>
<?= $form->field($model, 'subject')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'content')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'attachment')->fileInput(['maxlength' => 255]) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
and the controller:
public function actionCreate()
{
$model = new emails();
if ($model->load(Yii::$app->request->post())) {
// upload the attachment
$model->attachment = UploadedFile::getInstance($model, 'attachment');
if($model->attachment)
{
parent::init();
$time = time();
//$model->attachment->saveAs('attachments/'.$time.'.'.$model->attachment->extension);
//$model->attachment = 'attachments/'.$time.'.'.$model->attachment->extension;
}
if($model->attachment)
{
$value = Yii::$app->mailer->compose()
->setFrom(['my_email#gmail.com' => 'Paul'])
->setTo ($model->receiver_email)
->setSubject ($model->subject)
->setHtmlBody ($model->content);
foreach ($model->attachment as $file) {
//$filename = 'attachments/'.$time.'.'.$model->attachment->extension;
$filename = 'attachments/file.jpg';
//var_dump($filename);die();
$file->saveAs($filename);
$value->attach('attachments/file.jpg');
//$value->attach('attachments/'.$time.'.'.$model->attachment->extension);
}
$value->send();
}else{
$value = Yii::$app->mailer->compose()
->setFrom(['my_email#gmail.com' => 'Paul'])
->setTo($model->receiver_email)
->setSubject($model->subject)
->setHtmlBody($model->content)
->send();
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
I have tried absolute paths as well as dymanic paths, but all has the same output, i am stuck
Save as() function require the actual path. So that is issue. Please make sure your path should be correct and accessible.

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.

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.

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

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

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>