Yii CJuiAutoComplete values are not getting displayed - autocomplete

I apologise if this is already exists but i could not get it to work..
I need to show the names and store the id's in my table. these name are coming from other model(table). i'm getting the names and id's when i inspect elts in chrome network inspector..
but values are not not visible..but they are populating when i try to click on them its coming up in alert with id..
can anyone pls help me to get names visible --thanks for ur help
my _form.php is something like this:
<div class="row">
<?php echo $form->labelEx($typeModel,'benefit_type'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'attribute'=>'name',
'model'=>$typeModel,
'sourceUrl'=>array('benefit/benefit_type_list'),
'value'=>'Please select',
'name'=>'name',
'id'=>'id',
'options'=>array(
'minLength'=>'0',
'select'=>"js:function(event, ui) {
alert(ui.item.id);
// $('#organisation_id').val(ui.item.id);
}",
),
'htmlOptions'=>array(
'id'=>'id',
'size'=>45,
'maxlength'=>45,
),
)); ?>
<?php echo $form->error($typeModel,'benefit_type'); ?>
extension class for getting the names and id's is:
<? class EAutoCompleteAction extends CAction
{
public $model;
public $attribute;
public $id;
private $results = array();
public $returnVal = '';
public function run()
{
if(isset($this->model) && isset($this->attribute)) {
$criteria = new CDbCriteria();
$criteria->compare($this->attribute, $_GET['term'], true);
$model = new $this->model;
foreach($model->findAll($criteria) as $m)
{
// $this->results[] = $m->{$this->attribute};
//$this->results[] = $m-<{$this->id};
$this->results[] = array(
'name' => $m->{$this->attribute},
'id'=> $m->id
);
/* $this->returnVal .= $m->getAttribute('name').'|'
.$m->getAttribute('id'). "\n"; */
}
}
echo CJSON::encode($this->results);
}
}
?>
and in my controller:
public function actions()
{
return array(
'benefit_type_list'=>array(
'class'=>'application.extensions.EAutoCompleteAction',
'model'=>'BenefitType', //My model's class name
'attribute'=>'name', //The attribute of the model i will search
),
);
}

It's been a while since I used this extension but it uses Jquery's auto complete, and the dataset from EAutoCompleteAction probably needs:
$this->results[] = array(
'label' => $m->{$this->attribute},
'value'=> $m->id,
'id'=> $m->id
);
Source: yii forums

Related

Pass a value from controller to partial in ZF2

I want to pass some value from controller to view partial, basically, view partial is set using the placeholder in Application\Module.php, here is the code that does it.
<?php
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\View\Renderer\PhpRenderer;
use Zend\View\Resolver;
use Zend\ServiceManager\ServiceManager;
class Module
{
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH, array($this, 'initBreadcrumbAndActionButtonWidget'));
$moduleRouteListener->attach($eventManager);
$serviceManager = $e->getApplication()->getServiceManager();
}
public function initBreadcrumbAndActionButtonWidget(\Zend\Mvc\MvcEvent $e)
{
$serviceManager = $e->getApplication()->getServiceManager();
$config = $serviceManager->get('config');
$viewHelperManager = $this->getViewHelperManager($e->getApplication()->getServiceManager());
$partialHelper = $viewHelperManager->get('partial');
$partial = $partialHelper('widgets/breadcrumb', array(
'config' => $config,
'actionButtons' => $config['action-buttons']
));
$placeHolder = $viewHelperManager->get('placeholder');
$placeHolder('widgets/breadcrumb')->set($partial);
}
public function getViewHelperManager($serviceManager)
{
$stack = new Resolver\TemplatePathStack(array('script_paths' => array(__DIR__ . '/view/')));
$resolver = new Resolver\AggregateResolver();
$resolver->attach($stack);
$renderer = new PhpRenderer();
$renderer->setResolver($resolver);
$viewHelperManager = $serviceManager->get('ViewHelperManager');
return $viewHelperManager;
}
public function getConfig()
{
return array_merge_recursive(
include __DIR__ . '/config/module.config.php',
);
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
It is all working good till here, however now i want to pass a value from controller to the partial widgets/breadcrumb, after several attempt i thought implementing a ViewHelper could be a solution, and i implemented following view helper.
<?php
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
class Variable extends AbstractHelper
{
protected $data;
public function __invoke()
{
return $this;
}
public function set($identifier, $data)
{
$this->data[$identifier] = $data;
return $this;
}
public function get($identifier)
{
return $this->data[$identifier];
}
}
In controller i assign the value to ViewHelper like this.
$viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
$variable = $viewHelperManager->get('variable');
$variable->set('stack', 'overflow');
And in partial, to access the value i use the get method.
$this->variable()->get('stack');
Now my problem is that get() is rendered first hence the value set in controller has no effect.
My question is how can i make the set() gets rendered first so i can have the value in partial, or if there is any better approach of passing the value to partial please suggest.
Thanks.
Baaah, i called the view helper in wrong action, it worked when i moved the $variable->set('stack', 'overflow'); in the action where i wanted the value to pass.
Not sure if there can be a better solution, but this does the job for me to pass the value after i found no way in ZF2 that satisfies my requirement.

How to correctly address associations data in forms with cakephp 2.3

I am a pre-newbie with cakephp.
I have a "users" table and a "category" table
user belongsTo category (fields: users.id, users.name, users.category)
category hasMany users (fields: category.id, category.name, users.category)
I am addressing associating data like this.
in (users) edit.ctp I put
// view/Users/edit.ctp
echo $this->Form->input('name');
echo $this->Form->input('categories', array( 'value' => $this->Form->value('User.category'),
'name'=>'data[User][category]') );
</pre>
in users controller I have
<pre>
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
}
$sexes = $this->User->Sex->find('list');
$categories = $this->User->Category->find('list');
$this->set(compact('categories'));
}
Everything is working, but i suspect there's a much easier way to do that form.
Is this realy needed?
, array( 'value' => $this->Form->value('User.category'), 'name'=>'data[User][category]')
Without theese params the select box does not highlight the selected option, and nothing is saved.
Could be something like
echo $this->Form->input('Category.name');
for instance? But code like that does not show a select box.
And it doesn't save the users.category field.
I was not able to find any tutorial or code with samples about this.
Links would be appreciated.
Try to use Cake's nameing conventions for database tables and fields. If you follow the conventions Cake will do a lot of the heavy lifting for you:
users table:
users.id, users.name, users.category_id
categories table
categories.id, categories.name
User Model
class User extends AppModel {
public $belongsTo = array(
'Category'
);
}
Category Model
class Category extends AppModel {
public $hasMany = array(
'User'
);
}
Users Controller:
class UsersController extends AppController {
public function edit($id) {
if (!empty($this->request->data) {
// form submitted - try to save
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('User updated');
}
else {
$this->Session->setFlash('Please correct the errors');
}
}
else {
// prepopulate the form
$this->request->data = $this->User->findById($id);
}
// populate the categories dropdown
$this->set('categories', $this->User->Category->find('list');
}
}
/app/views/Users/edit.ctp
<?php
echo $this->Form->create();
echo $this->Form->inputs();
echo $this->Form->end('Update');

Zend Framework: Add form in layout

I create login form andd add in UserController->loginAction:
public function loginAction() {
$form = new Application_Form_Login();
$this->view->loginForm = $form;
}
How to add my form in layouts/scripts/header.phtml, because I try this, but not work:
<?php echo $this->loginForm ?>
If I echo form in views/scripts/user/login.phtml I see login form.
That is my login form:
class Application_Form_Login extends Zend_Form {
public function init() {
$this->setDecorators(array('FormElements', 'Form'))
->setAction("/user/login/");
$username = new Zend_Form_Element_Text(array('name' => 'username', 'class' => 'input-text'));
$username->setRequired(true)
->setDecorators(array('ViewHelper',));
$this->addElements(array($username));
}
}
You are looking for the render function:
<?php
echo $this->loginForm->render();
?>
Since a layout is separate from your view object, you need to assign the form to the layout.
In your controller:
public function loginAction()
{
$form = new Application_Form_Login();
// assign the form to the layout
$this->_helper->layout()->loginForm = $form;
}
In your layout:
<?php if ($this->layout()->loginForm): ?>
<?php echo $this->layout()->loginForm; ?>
<?php endif; ?>
Try this instead:
// in controller:
$form = new Application_Form_Login();
$this->view->placeholder('loginForm')->set($form);
---------------
// in layout script:
$form = $this->placeholder('loginForm');
if ($form instanceof Zend_Form) {
echo $form;
}

Fatal error: Class 'Form_BugReport' not found

I've been working through the Apress book 'Pro Zend Framework Techniques'. I've hit a point where I am trying to render the form on a view.
The form is called BugReport, which is located at forms/BugReportForm.php; here is the contents of the file:
<?php
class Form_BugReportForm extends Zend_Form
{
public function init()
{
// add element: author textbox
$author = this->createElement('text', 'author');
$author->setLabel('Enter your name:');
$author->setRequired(TRUE);
$author->setAttrib('size', 30);
$this->addElement($author);
// add element: email textbox
$email = $this->createElement('text', 'email');
$email->setLabel('Your email address:');
$email->setRequired(TRUE);
$email->addValidator(new Zend_Validate_EmailAddress());
$email->addFilters(array(
new Zend_Filter_StringTrim(),
new Zend_Filter_StringToLower()
));
$email = setAttrib('size', 40);
$this->addElement($email);
// add element: date textbox
$date = $this->createElement('text', 'date');
$date->setLabel('Date the issue occurred (dd-mm-yyyy)');
$date->setRequired(TRUE);
$date->addValidator(new Zend_Validate_Date('MM-DD-YYYY'));
$date->setAttrib('size', 20);
$this->addElement($date);
// add element: URL textbox
$url = $this->createElement('text', 'url');
$url->setLabel('Issue URL:');
$url->setRequired(TRUE);
$url->setAttrib('size', 50);
$this->addElement($url);
// add element: description text area
$description = $this->createElement('textarea', 'description');
$description->setLabel('Issue description:');
$description->setRequired(TRUE);
$description->setAttrib('cols', 50);
$description->setAttrib('rows', 4);
$this->addElement($description);
// add element: priority select box
$priority = $this->createElement('select', 'priority');
$priority->setLabel('Issue priority:');
$priority->setRequired(TRUE);
$priority->addMultiOptions(array(
'low' => 'Low',
'med' => 'Medium',
'high' => 'High'
));
$this->addElement($priority);
// add element: status select box
$status = $this->createElement('select', 'status');
$status->setLabel('Current status:');
$status->setRequired(TRUE);
$status->addMultiOptions(array(
'new' => 'New',
'in_progress' => 'In Progress',
'resolved' => 'Resolved'
));
$this->addElement($status);
// add element: submit button
$this->addElement('submit', 'submit', array('label' => 'Submit'));
}
}
This form in controlled via the BugController controller located at /controllers/BugController.php
<?php
class BugController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
public function createAction()
{
// action body
}
public function submitAction()
{
$frmBugReport = new Form_BugReport();
$frmBugReport->setAction('/bug/submit');
$frmBugReport->setMethod('post');
$this->view->form = $frmBugReport();
}
}
And finally I have the following autoloaders in my bootstrap.
protected function _initAutoload()
{
// Add autoloader empty namespace
$autoLoader = Zend_Loader_Autoloader::getInstance();
$resourceLoader = new Zend_Loader_Autoloader_Resource(array(
'basePath' => APPLICATION_PATH,
'namespace' => '',
'resourceTypes' => array(
'form' => array(
'path' => 'forms/',
'namespace' => 'Form_',
)
),
));
// Return it so it can be stored by the bootstrap
return $autoLoader;
}
The error I am getting can be seen here: http://zend.danielgroves.net/bug/submit
Or, if you'd rather just read it: Fatal error: Class 'Form_BugReport' not found in /home/www-data/zend.danielgroves.net/htdocs/application/controllers/BugController.php on line 23
Any ideas on what I've done wrong, and so how this can be fixed?
Edit
ArneRie pointed out I was using the wrong class name, but unfortunately this hasn't fixed the issue. Here's how BugController looks now:
<?php
class BugController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
public function createAction()
{
// action body
}
public function submitAction()
{
$frmBugReport = new Form_BugReportForm();
$frmBugReport->setAction('/bug/submit');
$frmBugReport->setMethod('post');
$this->view->form = $frmBugReport;
}
}
Although this did get rid of the error in question, a new one has taken it's place.
Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /home/www-data/zend.danielgroves.net/htdocs/application/forms/BugReportForm.php on line 8
Line 8 is interestingly /* Initialize action controller here */
You have a small typo. The bug is in your form. You are missing a $ before the "this" on line 9. Good luck with the rest of your project, it is a very good book for starters but there are a few small errors in it. Check the editors web site for details:http://www.apress.com/9781430218791/ in the errata section.
<?php
class Form_BugReportForm extends Zend_Form
{
public function init()
{
// add element: author textbox
//Next line is the line to change (add a $ before the "this")
$author = $this->createElement('text', 'author');
$author->setLabel('Enter your name:');
$author->setRequired(TRUE);
$author->setAttrib('size', 30);
$this->addElement($author);
Try it with: $frmBugReport = new Form_BugReportForm();
You're using the wrong class name.

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);
}