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);
Related
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;
}
),
)
}
i make a controller in zf2 for save data in mongodb but it not save any record in event table,how i save data?here is my code:
public function createAction()
{
$calendar_id = (int) $this->params()->fromRoute('id', 0);
if ($calendar_id == 0) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'index'
));
}
//echo $calendar_id;
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$form = new EventForm();
$update=false;
$message='';
$form->get('calendar_id')->setValue($id);
$form->get('submit')->setValue('Add');
if ($this->getRequest()->isPost()) {
$post = $this->getRequest()->getPost();
$form->setInputFilter($form->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$formData=$form->getData();
$s = new Event();
$s->setProperty('calendar_id',$calendar_id);
$s->setProperty('title',$post['title']);
$s->setProperty('description',$post['description']);
$s->setProperty('startdate',$post['begin']);
$s->setProperty('enddate',$post['end']);
$dm->persist($s);
$dm->flush();
$update=1;
$message='calendar Added Successfully.';
//$form = new CalendarForm();
//$this->redirect()->toRoute('calendar');
}
}
return array('form' => $form, 'add_message' => $message, 'update' => $update, 'calendar'=>$this->calendar);
}
I set code and save data using mongoodm,here is my code:
public function createAction()
{
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$calendar_id = (int) $this->params()->fromRoute('id', 0);
if ($calendar_id == 0) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'index'
));
}
$form = new EventForm();
$update=false;
$message='';
$form->get('calendar_id')->setValue($calendar_id);
$form->get('submit')->setValue('Add');
if ($this->getRequest()->isPost()) {
$post = $this->getRequest()->getPost();
$form->setInputFilter($form->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$formData=$form->getData();
$s = new Event();
$s->setProperty('calendar_id',$post['calendar_id']);
$s->setProperty('title',$post['title']);
$s->setProperty('description',$post['description']);
$s->setProperty('startdate',$post['begin']);
$s->setProperty('enddate',$post['end']);
$dm->persist($s);
$dm->flush();
$update=1;
$message='calendar Added Successfully.';
$form = new EventForm();
$this->redirect()->toRoute('calendar');
}
}
return array('form' => $form, 'add_message' => $message, 'update' => $update, 'calendar'=>$this->calendar);
}
I am new in zf2. I make a create action and want to get last inserted id but calender_id always equal to zero. How can I get the last insert id in create action ?
Here is my code:
public function createAction()
{
if ($this->zfcUserAuthentication()->hasIdentity())
{
$form = new CalendarForm();
$form->get('user_id')->setValue($this->zfcUserAuthentication()->getIdentity()->getId());
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost()) {
$calendar = new Calendar();
$form->setInputFilter($calendar->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$calendar->exchangeArray($form->getData());
$this->getCalendarTable()->saveCalendar($calendar);
if($request->isXmlHttpRequest()) {
//$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
//$calender = new \Calendar\Model\Calendar($dm);
$response = new Response();
$calender_id = $calendar->calendar_id;
$userid =$calendar->user_id;
$title=$calendar->title;
$description=$calendar->description;
$output = array('success' => true, 'calendar_id' => $calender_id, 'user_id' => $userid, 'title' => $title, 'description' => $description);
//$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
return $response;
}
return $this->redirect()->toRoute('calendar');
}
}
return array('form' => $form);
}
else
{
$this->redirect()->toRoute('zfcuser/login');
}
}
how i get last inserted id?
If your calendarTable extends TableGateway you can use $calendarTable->getLastInsertValue() to get the last insert id. You can also use this method in your saveCalendar method.
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!
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.