Zend Framework not deleting table entry - php

I am trying to delete a post from my table but the code is deleting all table data and not just the one post.
delete.php
<?php
class Form_Delete extends Zend_Form
{
public function __construct()
{
#parent::__construct($options);
$this->setName('Delete');
$id = new Zend_Form_Element_Hidden('id');
$title = new Zend_Form_Element_Hidden('Title');
$description = new Zend_Form_Element_Hidden('Description');
$submit = new Zend_Form_Element_Submit('Delete');
$submit->setAttrib('id', 'submitbutton');
$cancel = new Zend_Form_Element_Submit('cancel');
$cancel->setAttrib('id', 'cancelbutton');
$this->addElements( array( $id, $title, $description, $submit, $cancel ));
}
}
and my controller code
public function deleteAction()
{
//action body
$request = $this->getRequest();
$postid = (int)$request->getParam('id');
$post = new Model_DbTable_Posts();
$result = $post->getPost($postid);
$this->view->post = $result;
if(!Zend_Auth::getInstance()->hasIdentity()) {
$this->_redirect('posts/view/id/'.$postid);
}
$identity = Zend_Auth::getInstance()->getIdentity();
$acl = new Model_Acl();
if( $acl->isAllowed( $identity['Role'] ,'posts','edit','delete') ) {
$deleteForm = new Form_Delete();
$deleteModel = new Model_DbTable_Posts();
if ($this->getRequest()->isPost()) {
if ($deleteForm->isValid($request->getPost())) {
$deleteModel->delete($dpostid);
$this->_redirect('index/index');
}
}
$this->view->deleteForm = $deleteForm;
}
I have tried for hours to get this working but can ether get it to delete all or nothing. Any help would be great!

You need to pass delete() the where clause to evaluate. Try:
$where = $deleteModel->getAdapter()->quoteInto('id = ?', $dpostid);
$deleteModel->delete($where);
Change 'id' to whatever your primary key is.
Also #parent::__construct($options); in your form class is a little odd. Change that to parent::__construct();. No need to supress the error if you don't generate one.

Related

Zend Framework: How to save Objects from a select form to a database?

I started to work with Zend Framework 1.12.7 for a student project. I'm porgramming a User Class with an addAction and a form with various text fields and two dropdown menus that I want to fill with objects from the database (groups and roles). The idea is to select one object from the dropdown list (represented by its name) and save the id of the appropriate object to the database.
I already found out, that Zend Framework is working with associative arrays and I'm already able to select the names out of the dropdown menu. But however, there is still nothing saved to the database.
I provide you my controller, form and model code for the role object:
Controller:
public function addAction()
{
$request = $this->getRequest();
$rollen = new Application_Model_Rolle();
$mapper = new Application_Model_RolleMapper();
$rollen = $mapper->fetchAll();
$options;
foreach ($rollen as $rolle) {
$key = (string) $rolle->bezeichnung;
$options[] = array($key => $rolle->bezeichnung );
$values[] = array($key => $rolle);
}
$form = new Application_Form_Benutzer();
$form->getElement('rolle')->setMultiOptions($options);
$form->getElement('rolle')->setValues($values);
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$benutzerdaten = new Application_Model_Benutzer($form->getValues());
die($form->getValue('rolle'));
$mapper = new Application_Model_BenutzerMapper();
$mapper->save($benutzerdaten);
return $this->_helper->redirector('index');
}
}
Form:
$this->addElement('select', 'rolle', array(
'label' => 'Rolle:',
'required' => false,
));
Model:
public function fetchAll()
{
$resultSet = $this->getDbTable()->fetchAll();
$entries = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_Benutzer();
$entry->setb_Id($row->b_id)
->setNachname($row->nachname)
->setVorname($row->vorname)
->setBenutzername($row->benutzername)
->setEmail($row->email)
->setTelefon($row->telefon)
->setPasswort($row->passwort);
$gruppeID = $row->g_id;
$gruppe = new Application_Model_Gruppe();
$mapper = new Application_Model_GruppeMapper();
$gruppe = $mapper->find($gruppeID, $gruppe);
$rolleID = $row->r_id;
$rolle = new Application_Model_Rolle();
$mapper = new Application_Model_RolleMapper();
$rolle = $mapper->find($rolleID, $rolle);
$entry->setRolle($rolle);
$entry->setGruppe($gruppe);
$entries[] = $entry;
}
return $entries;
}
So how can I access the chose object and save its ID to the database?
Thank you very much for your help!
Cheers!
Martin

Validation for Add screen not working but it working in edit screen with same code

I am learning Zend framework and currently I have created add, update , delete functionality for country name and continent name and it is working perfectly.
I have set validation by
$name->setRequired('true');
and
$continent->setRequired('true');
in my form.php.
Validation is working in edit form but it return error 'An error occurred' and 'Application error' in add form.
Below is my controller code:
for Add:
/*Add Record into Database*/
public function addAction()
{
$form =new Application_Form_Add();
$form->submit->setlabel('Add Country');
$this->view->form = $form;
if($this->getRequest()->ispost())
{
$formData = $this->getRequest()->getpost();
if($form->isvalid($formData))
{
$file = new Application_Model_Country();
$name = $form->getvalue('name');
$continent = $form->getvalue('continent');
$file->addCountry($name, $continent);
$this->_helper->redirector('index');
}
else
{
$this->populate($formData);
}
}
}
for Edit:
/*Edit Record into Database*/
public function editAction()
{
$form = new Application_Form_Edit();
$form->submit->setlabel('Edit Country');
$this->view->form = $form;
if($this->getRequest()->ispost())
{
$formData = $this->getRequest()->getpost();
if($form->isvalid($formData))
{
$id = $form->getvalue('country_id');
$name = $form->getvalue('name');
$continent = $form->getvalue('continent');
$file = new Application_Model_Country();
$file->updateCountry($id,$name,$continent);
$this->_helper->redirector('index');
}
else
{
$form->populate($formData);
}
}
else
{
$id = $this->getRequest()->getparam('country_id');
if($id >0)
{
$formData = $this->getRequest()->getpost();
$file = new Application_Model_Country();
$files = $file->fetchRow('country_id='.$id);
$form->populate($files->toArray());
}
}
}
Both code are same, then why validation not working in add form?
You need to change following code in the addAction logic:
instead of:
$this->populate($formData);
use
$form->populate($formData);
The reason is $this means Action object in this context and you have correctly used $form object in EditAction so it is working properly, so it is kind of silly typing mistake.
PS: you should also use proper case in method names like isPost, isValidate etc. otherwise may get errors in Linux environment.

Fields getting NULL after editing

I have developed Zend 2 application. There is form to edit existing data. Some fields in table is not included in the form. Thus, when editing those records, fields not in form are saved as NULL. How to fix it ?
Model -
namespace Employee\Model;
class Employee
{
public $id;
public $active;
public $type;
public $mailing_address;
public $permanent_address;
...
public function exchangeArray($data)
{
$this->id = (isset($data['id'])) ? $data['id'] : 0;
$this->active = (isset($data['active'])) ? $data['active'] : 0;
$this->type = (isset($data['type'])) ? $data['type'] : null;
$this->mailing_address = (isset($data['mailing_address'])) ? $data['mailing_address'] : null;
$this->permanent_address = (isset($data['permanent_address'])) ? $data['permanent_address'] : null;
...
Table -
public function saveEmployee(Employee $employee) {
$data = array(
'active' => $employee->active,
'type' => $employee->type,
'mailing_address' => $employee->mailing_address,
'permanent_address' => $employee->permanent_address,
...
$id = (int) $employee->id;
if ($id == 0) {
$inserted = $this->tableGateway->insert($data);
$inserted_id = $this->tableGateway->lastInsertValue;
} else {
if ($this->getEmployee($id)) {
$this->tableGateway->update($data, array('id' => $id));
$inserted_id = $id;
} else {
throw new \Exception('Employee does not exist');
}
}
return $inserted_id;
//\Zend\Debug\Debug::dump($inserted_ids);
}
Controller -
$employeeForm = new EmployeeForm();
$employeeForm->bind($employee);
$request = $this->getRequest();
if ($request->isPost()) {
$employeeForm->setData($request->getPost());
if ($employeeForm->isValid()) {
$this->getEmployeeTable()->saveEmployee($employee);
}
}
Assume type dosn't have form filed defined. So, it shouldn't get NULL when save.
How to fix it ?
try handling it with mysql. use the [default] function of each field wisely
CREATE TABLE `table` (
`type` tinyint(3) unsigned NOT NULL default '0',
.......................
If you are editing an existing record then you would need to first load all the data for that entity and then update the fields that have changed. In ZF2 this is achieved via a form hydrator; as you bind the 'populated' object to the form.
Therefore your controller code would need to change.
EmpolyeeController.php
// Fetch the form from the service manager
// allowing it to be created via factory and have our
// hydrator and entity class injected
$form = $this->serviceLocator()->get('MyModule\Form\EmployeeForm');
$request = $this->getRequest();
$id = $this->params('id'); // Employee ID as route param
// Load the employee data from the database
// (this will vary dependning your own strategy, however
// a service layer is assumed)
$employee = $this->employeeService->findById($id);
// Bind the **hydrated** entity to the form
$form->bind($employee);
if ($request->isPost()) {
// set the modified post data
$form->setData($request->getPost());
if ($form->isValid()) {
// Retrive the validated and updated entity
$employee = $form->getData();
}
}
You will also need to register a form factory to inject the hydrator (an other dependancies).
Module.php
public function getFormElementConifg()
{
return array(
'factories' => array(
'MyModule\Form\EmployeeForm' => function($formElementManager) {
$serviceManager = $formElementManager->getServiceLocator();
$hydrator = $serviceManager->get('MyModule\Stdlib\Hydrator\EmployeeHydrator');
$form = new Form\EmployeeForm();
$form->setHydrator($hydrator);
$form->bind(new Entity\Employee());
return $form;
}
),
)
}

How to edit Zend form with edit button next to each field

I have file (ProfileController.php) which contains the following code:
public function editAction() {
if (Zend_Auth::getInstance()->hasIdentity()) {
try {
$form = new Application_Form_NewStory();
$request = $this->getRequest();
$story = new Application_Model_DbTable_Story();
$result = $story->find($request->getParam('id'));
// $values = array(
// 'names' => $result->names,
// 'password' => $result->password,
// );
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$data = array(
'names' => $form->getValue("names"),
'password' => $form->getValue("password"),
);
$form->populate($data->toArray());
$where = array(
'id' => $request->getParam('id'),
);
$story->update($data, $where);
}
}
$this->view->form = $form;
$this->view->titleS= $result->title;
$this->view->storyS= $result->story;
} catch (Exception $e) {
echo $e;
}
} else {
$this->_helper->redirector->goToRoute(array(
'controller' => 'auth',
'action' => 'index'
));
}
}
and another file (edit.phtml) with following code:
<?php
try
{
$tmp = $this->form->setAction($this->url());
//$tmp->titleS=$this->title;
//$tmp->storyS=$this->story;
//echo $tmp->title = "aaaaa";
}
catch(Exception $e)
{
echo $e;
}
?>
I would like the users to be able to edit their Username and password. How do I go about it?
First: move the Zend_Auth stuff up to init() or preDispatch(), that way Auth will run against any or all actions in the controller.
The trick in getting more then one submit button to work is to give the buttons different names so that getParam('') has something to work with.
Normally I only do this sort of thing when doing deletes, for edit's or update's I just submit the whole array back to the database. I typically use the Zend_Db_Table_Row save() method instead of Zend_Db_Table's insert() or update() so the mechanism is a little different.
I just use a simple form to perform an update, here is the controller code (the view just echo's the form):
//update album information
public function updatealbumAction()
{ //get page number from session
$session = new Zend_Session_Namespace('page');
//get album id
$id = $this->getRequest()->getParam('id');
$model = new Music_Model_Mapper_Album();
//fetch the album database record
$album = $model->findById($id);
$form = new Admin_Form_Album();
//this form is used elsewhere so set the form action to this action
$form->setAction('/admin/music/updatealbum/');
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();//get valid and filtered form values
$newAlbum = new Music_Model_Album($data);//create new entity object
$update = $model->saveAlbum($newAlbum);//save/update album info
$this->message->addMessage("Update of Album '$update->name' complete!");//generate flash message
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));//redirect back to the page the request came from
}
} else {
$form->populate($album->toArray());
$this->view->form = $form;
}
}
This is a pretty common update action.
Now here is how you might use different request parameters to perform an action on a record. I use this to delete database records but anything is possible.
public function deleteAction()
{
$session = new Zend_Session_Namespace('page');
$request = $this->getRequest()->getParams();
try {
switch ($request) {
//if
case isset($request['trackId']):
$id = $request['trackId'];
$model = new Music_Model_Mapper_Track();
$model->deleteTrack($id);
$this->message->addMessage("Track Deleted!");
break;
case isset($request['albumId']):
$id = $request['albumId'];
$model = new Music_Model_Mapper_Album();
$model->deletealbum($id);
$this->message->addMessage("Album Deleted!");
break;
case isset($request['artistId']):
$id = $request['artistId'];
$model = new Music_Model_Mapper_Artist();
$model->deleteArtist($id);
$this->message->addMessage("Artist Deleted!");
break;
default:
break;
}
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));
} catch (Exception $e) {
$this->message->addMessage($e->getMessage());
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));
}
}
you can pass the request parameters as submit button labels or as urls or whatever works for you.
Good Luck!

Why is Zend DB Update not posting?

Other modules in the application are updating, besides this one.
Here, I am using a model mapper in attempts to update a row set, as found in http://framework.zend.com/manual/en/learning.quickstart.create-model.html
public function SomeAction()
{
$mapper = new Application_Model_SomeMapper();
$model = new Application_Model_SomeModel(); //getters and setters
// action body
$request = $this->getRequest();
$data = $this->_request->getParams();
$someId = $data['someid'];
$get = $mapper->find($someId, new Application_Model_SomeModel, true); //find the row by id, and return array
/*
instantiating a form object and adding "submit"
*/
$form = new Module_Form_FormName();
$form->setAction("/module/controller/action/params/$someId");
$form->setMethod('post');
$form->setName('some_edit');
$submit = $form->createElement('button', 'submit');
$submit->setAttrib('ignore',true);
$submit->setLabel('Edit Something');
$form->addElement($submit);
if ($this->_request->isPost())
{
if($form->isValid($request->getPost()))
{
$data = $this->_request->getPost();
if(empty($data['some_id' ]))
{
$data['tier_models_id'] = NULL;
}
unset($data['submit']);
$setters = $model->setId($data['id'])
->setField1($data['field_1']);
if ($mapper->save($someId, $setters))
{
$this->_redirect("/index/");
}
}
}
$form->populate($tier);
$this->view->form = $get;
}
Here is an example of the save mapper function, except I've included an additional $id parameter
public function save(Application_Model_Guestbook $guestbook)
{
$data = array(
'email' => $guestbook->getEmail(),
'comment' => $guestbook->getComment(),
'created' => date('Y-m-d H:i:s'),
);
if (null === ($id = $guestbook->getId())) {
unset($data['id']);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('id = ?' => $id)); //not happening, although the 'id' is passed as a param
}
}
Is there something missing?
Try this instead
$where = $this->getDbTable()->getAdapter()->quoteInto('id = ?', $id);
$this->getDbTable()->update($data, $where);

Categories