zf2 : select columns dont work on tablegateway - select

I created the method 'fetchAll()' in my model in this way
public function fetchAll(){
$resultSet = $this->tableGateway->select( function (Select $select) {
$select->columns(array('my_alias'=>'my_field'));
});
return $resultSet;
}
so, i get the results in controller
...
$items = $this->getMyTable()->fetchAll();
...
and i sendo to my action
...
foreach( $items => $item ){ print $item->my_alias; }
...
but '$item->my_alias' is not defined. Without 'columns' method, its work. Whats wrong ?

try this
public function fetchAll(){
$select = new Select();
$select->from('table');
$select->columns(array('my_alias' => 'my_field'));
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}

Related

Codeigniter Call to a member function where() on bool

I tried to set seen to any contact data in database, but when i try that:
public function showMessage($id){
$this->load->model('Message_Model');
$messageData = $this->Message_Model->selectMessage($id);
if($messageData[0]->messageIsSeen == 0){
$this->Message_Model->setSeenToMessage($id);
}
$data = array('messageData' => $messageData[0]);
$this->load->view('Back/MessageDetail', $data);
}
Model:
function setSeenToMessage($id){
$this->db->update('messages', array('messageIsSeen' => 1))->where('messageId', $id);
return 1;
}
It throws that error
i solved it like this change
function setSeenToMessage($id){
$this->db
->where('messageId', $id);
->update('messages', array('messageIsSeen' => 1))
return 1;
}
nevertheless, still i don't know how did it works

Zend2 TableGateway: how to retrieve a set of data

I have a ContactsTable.php module and an function like this:
public function getContactsByLastName($last_name){
$rowset = $this->tableGateway->select(array('last_name' => $last_name));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row record");
}
return $row;
}
which is ok, but it only returns one row.
The problem is in my database I have multiple records with the same Last Name, so my question is:
How can I return a set of data?
I tried this:
$where = new Where();
$where->like('last_name', $last_name);
$resultSet = $this->tableGateway->select($where);
return $resultSet;
but it doesn't work.
Your first function should work as you expect, just remove line
$row = $rowset->current();
So, complete function should look like this:
public function getContactsByLastName($last_name){
$rowset = $this->tableGateway->select(array('last_name' => $last_name));
foreach ($rowset as $row) {
echo $row['id'] . PHP_EOL;
}
}
More info you can find in documentation http://framework.zend.com/manual/2.2/en/modules/zend.db.table-gateway.html
You can use the resultset to get array of rows:
public function getContactsByLastName($last_name) {
$select = new Select();
$select->from(array('u' => 'tbl_users'))
->where(array('u.last_name' => $last_name));
$statement = $this->adapter->createStatement();
$select->prepareStatement($this->adapter, $statement);
$result = $statement->execute();
$rows = array();
if ($result->count()) {
$rows = new ResultSet();
return $rows->initialize($result)->toArray();
}
return $rows;
}
Its working for me.

concatenate fields with zend_form

I'm using the zend framework with centurion and I'm having a problem with my form. I have fields num_ordre and code, both of which are primary keys and I have columns in my table named conca, it's the concatenation of two fields, num_ordre and code.
My question is, in my method post, I want to test if the concatanation of num_ordre and code already exists in my database; but the problem is how to take a value of to fields before posting it.
This is my code
public function postAction(){
$this->_helper->viewRenderer->setNoRender(TRUE);
$user = new Param_Model_DbTable_Verification();
$form= $this->_getForm();
$form->getElement('Num_ordre')->addValidator(new Zend_Validate_Db_NoRecordExists('verifications','Num_ordre'));
$form->getElement('Num_ordre')->setRequired(true);
$posts = $this->_request->getPost();
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$row=$user->createRow();
$row->code=$this->_getParam('code');
$row->Num_ordre=$this->_getParam('Num_ordre');
$row->Libelle_champ=$this->_getParam('Libelle_champ');
$row->comparaison=$this->_getParam('comparaison');
$row->formule=$this->_getParam('formule');
$row->obligatoire=$this->_getParam('obligatoire');
$row->Req_traduction=$this->_getParam('Req_traduction');
$row->tolerance_erreur=$this->_getParam('tolerance_erreur');
$row->Mess_erreur=$this->_getParam('Mess_erreur');
$row->conca=$this->_getParam('Num_ordre').$this->_getParam('code');
$row->save();
if( isset ($posts['_addanother'])){
$_form = $this->_getForm();
$_form->removeElement('id');
$this->_helper->redirector('new','admin-verification');
}
else
$this->_helper->redirector(array('controller'=>'Admin-verification'));
}else{
parent::postAction();
}
}}
How about you just check it like this ?
public function postAction(){
$this->_helper->viewRenderer->setNoRender(TRUE);
$user = new Param_Model_DbTable_Verification();
$form= $this->_getForm();
$form->getElement('Num_ordre')->addValidator(new Zend_Validate_Db_NoRecordExists('verifications','Num_ordre'));
$form->getElement('Num_ordre')->setRequired(true);
$posts = $this->_request->getPost();
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
$mdl = new Model_Something(); //Call your model so you can test it
//Add a condition here
if ($form->isValid($formData) && $mdl->uniqueConcatenated($this->_getParam('num_ordre'), $this->_getParam('code')) {
$row=$user->createRow();
/**truncated, keep your existing code here**/
}
}
}
Then in your model Model_Something
public function uniqueConcatenated($numOrder, $code) {
$concatenated = $numOrder.$code;
//Check for the existence of a row with the concatenated field values
$select = $this->select();
$select->where('concatenatedField = '.$concatenated);
$row = $this->fetchRow($select);
return $row;
}
Hope this helps
You could manually call isValid on the validator:
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$formValues = $form->getValues();
$uniqueValidator = new Zend_Validate_Db_NoRecordExists('verifications','conca');
if ($uniqueValidator->isValid($formValues['Num_ordre'] . $formValues['Num_ordre'])) {
// valid
} else {
// not unique
}
}
untested code

Zend db select how to know return zero rows?

This is my code:
public function is_existing($url) {
$query = $this->select()
->where("url=?",$url);
if(!$query) {
return false;
} else {
$row = $this->fetchRow($query);
$row = $row->toArray();
return $row;
}
}
But sometimes, I receive
Fatal error: Call to a member function toArray() on a non-object in...
Is it right to use if(!$query) to check the existing rows in DB?
Change your code to this
public function is_existing($url) {
$query = $this->select()
->where("url=?",$url);
$row = $this->fetchRow($query);
if(!$row) {
return false;
} else {
return $row->toArray();
}
}
Because $query object will always be created irrespective $url matches record or not hence will always pass if condition .
Is it right to use if(!$query) to check the existing rows in DB ?
No, you should evaluate the result of fetchRow to determine if there are results, fetchRow either returns a Zend_Db_Table_Row or null if no rows are found.
public function is_existing($url) {
$query = $this->select()
->where("url=?",$url);
$row = $this->fetchRow($query);
if(is_null($row)) {
return false;
} else {
return $row->toArray();
}
}

Database expression not used in query

Can anyone tell me why my expression is not used in the query below?
SELECT accountreset.* FROM accountreset WHERE (reset_id = '34') LIMIT 1
public function findByResetId($resetId, $model = null) {
$result = null;
if (isset($resetId)) {
$select = $this->getDao()->select(
array('expiration' => new Zend_Db_Expr('UNIX_TIMESTAMP(expiration)'))
);
$select->where('reset_id = ?', $resetId);
$row = $this->getDao()->fetchRow($select);
if (null != $row) {
if (!($model instanceof Stage5_Model_PasswordResetter)) {
$model = new Stage5_Model_PasswordResetter();
}
// vul het model object
$model->setResetId($row->reset_id);
$model->setUserId($row->user_id);
$model->setExpiration($row->expiration);
$result = $model;
}
}
return $result;
}
Your Zend_Db_Expr should go into from() method instead of select()
$select = $this->getDao()
->select()
->from(
$this->getDao()->info('name'),
array('expiration' => new Zend_Db_Expr('UNIX_TIMESTAMP(expiration)'))
);