Zend Framework Adding Search Option - zend-framework

I am new to the Zend Framwork. I would like to add search function on the existing module. When the user enters the name in the textbox it should return the corresponding record. Could someone help me to add this function?
Thanks
PS: I don't want to use lucene

use this function:
define thes variable in your model
and add this function
protected $_name = 'your_table_name';// table name
public function getAll($order = null, $count = null, $offset = null) {
$rows = $this->fetchAll(NULL, $order, $count, $offset);
return $rows->toArray();
}

Related

how to use backpack clone feature for unique field form

Backpack Crud have clone function. But it isn't work when our table has unique field column.
Backpack clone Documentation
When table has unique column how to clone it?
public function clone($id)
{
$this->crud->hasAccessOrFail('clone');
$this->crud->setOperation('clone');
$clonedEntry = $this->crud->model->findOrFail($id)->replicate();
return (string) $clonedEntry->push();
}
Recently I experienced the same problem. Here is my solution:
public function clone($id)
{
$this->crud->hasAccessOrFail('clone');
$this->crud->setOperation('clone');
$clonedEntry = $this->crud->model->findOrFail($id)->replicate();
// now resolve the value for unique attribute before save. e.g.
$slug = Str::slug($clonedEntry->name, '-');
$count = $this->crud->model->whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();
$clonedEntry->slug = $count ? "{$slug}-{$count}" : $slug;
// when you are done, save changes
return (string) $clonedEntry->push();
}
You didn't specify anything about that "unique" attribute. Feel free to customize the resolver according your needs.

Zend Framework: Form Validation - Please Fill In 'A' or 'B'

I'm writing an application with Zend Framework. I have a simple form that has two text boxes.
How do I add validation to the form so that at least one of the input boxes should be populated?
You could create a custom validator, something like:
class My_Validate_AtLeastOneNotEmpty implements Zend_Validate_Interface
{
protected $thisField;
protected $otherField;
protected $messages = array();
public function __construct($thisField, $otherField){
$this->thisField = $thisField;
$this->otherField = $otherField;
}
public function isValid($value, $context = null)
{
$validator = new Zend_Validate_NotEmpty();
if (!$validator->isValid($value) && !$validator->isValid($context['otherField'])){
$this->messages[] = 'At least one of the fields - '
. $thisField . ' or ' . $otherField
. ' - must be non-empty';
return false;
}
return true;
}
public function getMessages()
{
return $this->messages;
}
}
Then attach this validator to one of the elements, identifying both names:
// create the two fields
$fld1 = new Zend_Form_Element_Text('field1');
$fld2 = new Zend_Form_Element_Text('field2');
// add the validator to one of them, identifying both fields
$fld1->addValidator(new My_Validate_AtLeastOneNotEmpty('field1', 'field2'));
Typically, we would not need to identify the fieldname of the element to which we are attaching the validator. However, by passing both fieldnames to the validator, we can make the error message a little clearer for the user.
Create a radio group with two options, both unchecked. Hide the textfields. With an onclick event on the radio buttons you can show one of the textboxes. Now you can add a required validator to the radio buttons. A little workaround, but the result is the same.

Zend duplicated rows on mysql insert

For some reason, when I do an mysql db insert from Zend, my row is dulpicated. I've tried a direct insert via phpmyadmin and it works perfect, so its not a mysql server problem.
This is the code I use:
<?php
class Model_Team extends Zend_Db_Table_Abstract {
protected $_name = 'team';
public function createUser($data) {
$user = $this->createRow();
$user->name = $data['name'];
$user->title = $data['title'];
$id = $user->save();
return $id;
}
}
?>
Thanks in advance.
EDIT:
I've found that this duplication only occurs when i call the form via AJAX (modal box), although the form post is normal, not an ajax request)
I don't know why your code is double pumping the database on save but it should'nt matter as you're using the Row object and save(). (save() inserts or updates)
You may want to restructure your createUser() function so that it can't create a new row if the row already exists.
<?php
class Model_Team extends Zend_Db_Table_Abstract {
protected $_name = 'team';
public function createUser(array $data) {
$user = $this->createRow();
//test if user has id in the array
if (array_key_exists('id', $data)){
$user->id = $data['id'];
}
$user->name = $data['name'];
$user->title = $data['title'];
$user->save();
//no need to create a new variable to return the user row
return $user;
}
}
This method will create and update a user row.
To help you further I'll need to see the controller code most of my double pumps have happened there.
Instead of using createRow() have you tried using insert()?
/**
* Insert array of data as new row into database
* #param array $data associative array of column => value pairs.
* #return int Primary Key of inserted row
*/
public function createUser($data)
{
return $this->insert($data);
}
Also - could we see the ajax code? It may be that the form is being posted as well?

zend relationships with select

I am new to zend. I have been asked to redevelop a website that was once written in plain PHP and put it into the zend framework.
I am having a lot of trouble with database relationships, I cant seem to get my head round defining and querying relationships.
I would like to find a Category. From that Category I would like to be able to find all the CategoryInfo associated with it, and be able to query/sort/limit that dataset.
Here are my models.
Categorys.php
<?php
class Default_Model_Categorys extends Zend_Db_Table_Abstract
{
protected $_name = 'Categorys';
protected $_primary = 'id';
protected $_dependentTables = array('Default_Model_CategoryInfo');
}
?>
CategoryInfo.php
<?php
class Default_Model_CategoryInfo extends Zend_Db_Table_Abstract
{
protected $_name = 'Category_Info';
protected $_primary = 'id';
protected $_referenceMap = array(
'Categorys' => array(
'columns' => array('cat_id'),
'refTableClass' => 'Default_Model_Categorys',
'refColumns' => array('id')
)
);
}
?>
CategoryController.php
<?php
class CategorysController extends Zend_Controller_Action
{
public function indexAction()
{
/*
this should redirect to all games
*/
return $this->_forward("index", "games");
}
public function categoryAction()
{
/*
shows a specific category
*/
$id = (int) $this->_request->getParam('id');
$category = new Default_Model_Categorys();
$this->view->category = $category->fetchRow(
$category->select()->where('id = ?', $id)
);
$categoryInfo = $this->view->category->findDependentRowset('Default_Model_CategoryInfo');
}
}
Firstly... am I doing anything wrong?
Secondly... how do I go about querying the dependent rowset?
First, if you're searching for a category by its primary key, it's simpler to use the find() method:
$id = (int) $this->_request->getParam('id');
$category = new Default_Model_Categorys();
$this->view->category = $category->find($id)->current();
Second, to restrict or sort dependent Category_Info rows, you can use a Zend_Db_Table_Select object as an optional parameter of findDependentRowset(). Here's an example:
$select = $category->select()->where("info_type = 'PRICE'")
->order("info_date")
->limit(3);
$categoryInfo = $this->view->category->findDependentRowset(
'Default_Model_CategoryInfo', null, $select);
Notice you can use any table object to create that select object. Since the "FROM" clause for that select will be set by the findDependentRowset() method, you just add other clauses and then pass it in.
PS: You don't need to declare $_dependentTables at all, unless you're going to use cascading update or cascading delete via PHP code. I recommend strongly against doing that -- it's far more efficient to let the RDBMS handle those cascading operations.
Likewise you should never have to declare $_primary if your database tables actually declare primary key constraints. Zend_Db_Table_Abstract knows how to inspect metadata to get the primary key column(s).
Everything looks correctly to me. You don't query a dependent rowset. It is a query itself and it returns a result set. Basically what it is doing is pulling all records related to the current row you are working with as defined by $_referenceMap. Once you execute findDependentRowset(), you can foreach over the results which will give you instances of Zend_Db_Table_Row. From there you can display the related data as needed.
Personally I don't use Zend_Db Relationships. It is much easier to just make a second model method to query what I need. Also, Zend_Db Relationships do not support where clauses, so just making a second query is much more flexible than relationships.

Using relations for setting in Zend_Db_Table_Row

is there a way how to use Zend_Db relations for setting related objects?
I am looking for something like following code:
$contentModel = new Content();
$categoryModel = new Category();
$category = $categoryModel->createRow();
$category->setName('Name Category 4');
$content = $contentModel->createRow();
$content->setTitle('Title 4');
$content->setCategory($category);
$content->save();
this provides small library:
http://code.google.com/p/zend-framework-orm/
does somebody have experience with that? Isn't there a plan for something similar in ZF ? Or is there something better for use? (I don't wnat to use doctrine ORM or something external)
thanks
I designed and implemented the table-relationships code in Zend Framework.
A foreign key ($content->category in your example) contains the value of the the primary key in the parent row it references. In your example, the $category doesn't contain a primary key value yet because you haven't saved it (assuming it uses an auto-incrementing pseudokey). You can't save the $content row until you populate its foreign key, so referential integrity is satisfied:
$contentModel = new Content();
$categoryModel = new Category();
$category = $categoryModel->createRow();
$category->setName('Name Category 4');
$content = $contentModel->createRow();
$content->setTitle('Title 4');
// saving populates the primary key field in the Row object
$category->save();
$content->setCategory($category->category_id);
$content->save();
It would do no good to pass the Row object to setCategory() if it doesn't have the primary key populated. $content->save() will fail if it doesn't have a valid primary key value to reference.
Since you need that primary key field to be populated in any case, it's not so difficult to access the field when you call setCategory().
I always override Zend_Db_Table and Zend_Db_Table_Row and use my own subclasses. In my Db_Table class I have:
protected $_rowClass = 'Db_Table_Row';
In my Db_Table_Row I have the following __get() and __set() functions:
public function __get($key)
{
$inflector = new Zend_Filter_Word_UnderscoreToCamelCase();
$method = 'get' . $inflector->filter($key);
if(method_exists($this, $method)) {
return $this->{$method}();
}
return parent::__get($key);
}
public function __set($key, $value)
{
$inflector = new Zend_Filter_Word_UnderscoreToCamelCase();
$method = 'set' . $inflector->filter($key);
if(method_exists($this, $method))
return $this->{$method}($value);
return parent::__set($key, $value);
}
Bascially that just tells the class to look for methods called getFoo() and setFoo() or whatever. You could then pretty much make up your own fields as long as your write your own logic behind. In you case maybe:
public function setCategory($value)
{
$this->category_id = $value->category_id;
}