I am doing an e-commerce site, and in the end I realized a bug when modifying the informations of the customers informations:
the error is as follows:
Uncaught PHP Exception Error: "Call to a member function getId() on null"
at C:\wamp64\www\caviar-pro\src\Controller\CustomerController.php line 339
Here is the part of the code that is problematic:
The complete code is the following:
public function updateAction(Request $request): Response
{
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$this->isGrantedOr403($configuration, ResourceActions::UPDATE);
$resource = $this->findOr404($configuration);
$form = $this->resourceFormFactory->create($configuration, $resource);
$oldInfo = clone $resource;
$oldAddressInfo = $oldInfo->getDefaultAddress() ? clone $oldInfo->getDefaultAddress() : null;
if (in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'], true) && $form->handleRequest($request)->isValid()) {
/** #var CustomerInterface $resource */
$resource = $form->getData();
$defaultAddress = $resource->getDefaultAddress();
if (!$defaultAddress->getId()) {
$defaultAddress->setFirstName($resource->getFirstName());
$defaultAddress->setLastName($resource->getLastName());
}
/** #var ResourceControllerEvent $event */
$event = $this->eventDispatcher->dispatchPreEvent(ResourceActions::UPDATE, $configuration, $resource);
if ($event->isStopped() && !$configuration->isHtmlRequest()) {
throw new HttpException($event->getErrorCode(), $event->getMessage());
}
if ($event->isStopped()) {
$this->flashHelper->addFlashFromEvent($configuration, $event);
if ($event->hasResponse()) {
return $event->getResponse();
}
return $this->redirectHandler->redirectToResource($configuration, $resource);
}
try {
$this->resourceUpdateHandler->handle($resource, $configuration, $this->manager);
$valueChangedPersonnalInfo = $this->compareCustomer($oldInfo, $resource);
$valueChangedAddress = $oldAddressInfo ? $this->compareAddressCustomer($oldAddressInfo, $resource->getDefaultAddress()) : [];
$valueChanged = array_merge($valueChangedPersonnalInfo, $valueChangedAddress);
/*sending email according to template bo*/
/** #var Email $email */
$email = $this->manager->getRepository('App\Entity\Email\Email')->findOneByCode(MailerManager::ACCOUNT_MODIFICATION_MAILER_CODE);
$user = $this->getUser();
$emailManager = $this->emailManager->letterParagraphBy($email->getContent(), $email, $user->getCustomer());
$emailToSend = $this->renderView('#SyliusShop/Email/userInfoChange.html.twig', [
'infoChanged' => $valueChanged,
'email' => $email,
'emailManager' => $emailManager,
]);
$emailFrom = [$email->getFromEmail() => $email->getFromName()];
$this->mailerManager->sendMail($resource->getEmail(), $email->getSubject(), $emailToSend, $emailFrom);
} catch (UpdateHandlingException $exception) {
if (!$configuration->isHtmlRequest()) {
return $this->viewHandler->handle(
$configuration,
View::create($form, $exception->getApiResponseCode())
);
}
$this->flashHelper->addErrorFlash($configuration, $exception->getFlash());
return $this->redirectHandler->redirectToReferer($configuration);
}
$postEvent = $this->eventDispatcher->dispatchPostEvent(ResourceActions::UPDATE, $configuration, $resource);
if (!$configuration->isHtmlRequest()) {
$view = $configuration->getParameters()->get('return_content', false) ? View::create($resource, Response::HTTP_OK) : View::create(null, Response::HTTP_NO_CONTENT);
return $this->viewHandler->handle($configuration, $view);
}
$this->flashHelper->addSuccessFlash($configuration, ResourceActions::UPDATE, $resource);
if ($postEvent->hasResponse()) {
return $postEvent->getResponse();
}
return $this->redirectHandler->redirectToResource($configuration, $resource);
}
if (!$configuration->isHtmlRequest()) {
return $this->viewHandler->handle($configuration, View::create($form, Response::HTTP_BAD_REQUEST));
}
$initializeEvent = $this->eventDispatcher->dispatchInitializeEvent(ResourceActions::UPDATE, $configuration, $resource);
if ($initializeEvent->hasResponse()) {
return $initializeEvent->getResponse();
}
$carrousels = $this->manager->getRepository(Carrousel::class)->findOneBy(['code' => 'my_account_carrousel', 'enabled' => true]);
$view = View::create()
->setData([
'configuration' => $configuration,
'metadata' => $this->metadata,
'resource' => $resource,
$this->metadata->getName() => $resource,
'form' => $form->createView(),
'carrousels' => $carrousels,
])
->setTemplate($configuration->getTemplate(ResourceActions::UPDATE . '.html'))
;
return $this->viewHandler->handle($configuration, $view);
}
If someone could tell me the solution to my problem I'm interested because I'm stuck on this part of my site for a while.
By !$defaultAddress->getId(), id will always exists except the entity is not yet persisted or null.
On you case, $defaultAddress is null. (dump the variable to see).
I think, you should do something like:
if (!$defaultAddress) {
$defaultAddress = new AddressObject(); //change this to your address class
$defaultAddress->setFirstName($resource->getFirstName());
$defaultAddress->setLastName($resource->getLastName());
}
Related
In my project I want to use the object created by my precedent form:
Here is the schema of my database:
My QuizController
public function creation(Request $request){
$quiz = new Quiz();
$user = $this->getUser();
$formQuiz = $this->createForm(QuizType::class, $quiz);
$formQuiz->handleRequest($request);
if ($formQuiz->isSubmitted() && $formQuiz->isValid() ) {
$quiz->setCreatedAt(new DateTimeImmutable());
$quiz->setCreatedBy($user);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($quiz);
$entityManager->flush();
return $this->redirectToRoute('creation_questions');
}
return $this->render('quiz/creation.html.twig', [
'formQuiz' => $formQuiz->createView(),
]);
}
And my QuestionController that must be connected with the quiz form
public function creation_questions(Request $request){
$quiz = ?
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid() ) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
What do I have to write in place of the '?'?
You don't show your routing but you could use paramConverte "magic" from SensioFrameworkExtraBundle and do something like this.
/**
* #Route("/some-route/{id}", name="some_route_name")
*/
public function creation_questions(Request $request, Quiz $quiz)
{
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid()) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
Where the {id} part of /someRoute/{id} is the Quiz Id. Symfony should automagically fetch the Quiz matching that id. Or you can be more explicit about how the param converter should interpret such a value. More info here https://symfony.com/bundles/SensioFrameworkExtraBundle/current/annotations/converters.html
Alternatively, you could pass the quiz id and fetch the quiz manually (less magic but totally legit).
/**
* #Route("/some-route/{id}", name="some_route_name")
*/
public function creation_questions(Request $request, int $id)
{
$entityManager = $this->getDoctrine()->getManager();
$quiz = $entityManager->getRepository(Quiz::class)->find($id);
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid()) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
This piece of code shows a smll part of the models post.php from October Rainlab Blog plugin. The AfterSave() function is modified, it sends an e-mail when a new blogPost in the backend is saved by the administrator, however, I would like to send it when it is actually Published and make sure it is not sending multiple times. How could I accomplish this?
public function filterFields($fields, $context = null)
{
if (!isset($fields->published, $fields->published_at)) {
return;
}
$user = BackendAuth::getUser();
if (!$user->hasAnyAccess(['rainlab.blog.access_publish'])) {
$fields->published->hidden = true;
$fields->published_at->hidden = true;
}
else {
$fields->published->hidden = false;
$fields->published_at->hidden = false;
}
}
public function afterValidate()
{
if ($this->published && !$this->published_at) {
throw new ValidationException([
'published_at' => Lang::get('rainlab.blog::lang.post.published_validation')
]);
}
}
public function beforeSave()
{
if (empty($this->user)) {
$user = BackendAuth::getUser();
if (!is_null($user)) {
$this->user = $user->id;
}
}
$this->content_html = self::formatHtml($this->content);
}
public function afterSave()
{
$user = BackendAuth::getUser();
if ($user && $user->hasAnyAccess(['rainlab.blog.access_publish'])) {
$susers = Db::select('select * from users where is_activated = ?', [1]);
foreach ($susers as $suser) {
$currentPath = $_SERVER['PHP_SELF'];
$pathInfo = pathinfo($currentPath);
$hostName = $_SERVER['HTTP_HOST'];
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
$protocol.'://'.$hostName.$pathInfo['dirname']."/";
$spost_url = $protocol.'://'.$hostName.$pathInfo['dirname']."/"."nieuws/".$this->attributes['slug'] ;
$stitle = $this->attributes['title'] ;
$body = '<div> Hallo '.$suser->name.'</br> Er is zojuist een nieuws bericht gepubliceerd voor alle leden van mycompany.nl , je kunt hier het bericht lezen aangaande: '.$stitle.' </div>' ;
//$from = $user->email ;
$from = 'noreply#mycompany.nl';
$headers = "From: $from\r\n";
$headers .= "Content-type: text/html\r\n";
mail($suser->email,'Nieuws van mycompany', $body,$headers);
}
}
}
/**
* Sets the "url" attribute with a URL to this object.
* #param string $pageName
* #param Controller $controller
* #param array $params Override request URL parameters
*
* #return string
*/
public function setUrl($pageName, $controller, $params = [])
{
$params = array_merge([
'id' => $this->id,
'slug' => $this->slug,
], $params);
if (empty($params['category'])) {
$params['category'] = $this->categories->count() ? $this->categories->first()->slug : null;
}
// Expose published year, month and day as URL parameters.
if ($this->published) {
$params['year'] = $this->published_at->format('Y');
$params['month'] = $this->published_at->format('m');
$params['day'] = $this->published_at->format('d');
}
return $this->url = $controller->pageUrl($pageName, $params);
}
/**
* Used to test if a certain user has permission to edit post,
* returns TRUE if the user is the owner or has other posts access.
* #param User $user
* #return bool
*/
public function canEdit(User $user)
{
return ($this->user_id == $user->id) || $user->hasAnyAccess(['rainlab.blog.access_other_posts']);
}
public static function formatHtml($input, $preview = false)
{
$result = Markdown::parse(trim($input));
// Check to see if the HTML should be cleaned from potential XSS
$user = BackendAuth::getUser();
if (!$user || !$user->hasAccess('backend.allow_unsafe_markdown')) {
$result = Html::clean($result);
}
if ($preview) {
$result = str_replace('<pre>', '<pre class="prettyprint">', $result);
}
$result = TagProcessor::instance()->processTags($result, $preview);
return $result;
}
//
// Scopes
//
public function scopeIsPublished($query)
{
return $query
->whereNotNull('published')
->where('published', true)
->whereNotNull('published_at')
->where('published_at', '<', Carbon::now())
;
}
/**
* Lists posts for the frontend
*
* #param $query
* #param array $options Display options
* #return Post
*/
public function scopeListFrontEnd($query, $options)
{
/*
* Default options
*/
extract(array_merge([
'page' => 1,
'perPage' => 30,
'sort' => 'created_at',
'categories' => null,
'exceptCategories' => null,
'category' => null,
'search' => '',
'published' => true,
'exceptPost' => null
], $options));
$searchableFields = ['title', 'slug', 'excerpt', 'content'];
if ($published) {
$query->isPublished();
}
One way to accomplish this would be to extend the Post model.
As an example, you create a new plugin and model with an is_notified field.
You would then add something like this to the boot() method of your new plugin:
PostModel::extend(function ($model) {
$model->hasOne['your_model'] = ['Author\PluginName\Models\YourModel'];
});
PostsController::extendFormFields(function ($form, $model, $context) {
// Checking for Post instance
if (!$model instanceof PostModel) {
return;
}
// without this code you can get an error saying "Call to a member function hasRelation() on null"
if (!$model->your_model) {
$model->your_model = new YourModel;
}
}
You can then use that new model in the afterSave method
public function afterSave()
{
$user = BackendAuth::getUser();
if ($user && $user->hasAnyAccess(['rainlab.blog.access_publish'])) {
$susers = Db::select('select * from users where is_activated = ?', [1]);
foreach ($susers as $suser) {
...
if ($this->your_model->is_notified != true) {
mail($suser->email,'Nieuws van mycompany', $body,$headers);
$this->your_model->is_notified = true;
}
}
}
}
You should also consider using the extend method instead of modifying 3rd party plugin code. This will allow you to update the plugin without losing your edits. Something like this:
PostModel::extend(function ($model) {
$model->hasOne['your_model'] = ['Author\PluginName\Models\YourModel'];
// You can transfer your afterSave code here!
$model->bindEvent('model.afterSave', function () use ($model) {
$user = BackendAuth::getUser();
if ($user && $user->hasAnyAccess(['rainlab.blog.access_publish'])) {
..
}
});
});
Let me know if you have any questions!
I want to click on an image opens the window for selecting a new image, and change the screen, now I want to change this picture in the bank, but this pending on an error:
Catchable Fatal Error: Argument 1 passed to
Delivve\WebBundle\Entity\User::setFile() must be an instance of
Symfony\Component\HttpFoundation\File\UploadedFile, string given,
called in
/home/delivve-webservice/src/Delivve/WebBundle/Controller/UserController.php
I do not know whether the error is in the path image that I'm taking?
$("#bundle_user_file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.active-img').attr('src', e.target.result);
ajax_formData(e.target.result);
};
reader.readAsDataURL(this.files[0]);
}
});
function ajax_formData(image) {
var path = "{{ path("submit_image_user", {"userId" : owner.id}) }}";
alert(image);
$.post(path, {image: image}, function (data) {
alert(data.message);
}, "json");
}
public function submitImageAction(Request $request, $userId){
$this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');
$em = $this->getDoctrine()->getManager();
$entity = $this->getUser();
if ($entity->getId() != $userId) {
$response = new JsonResponse(
array(
'message' => "Não tem permissão de alterar esses dados"
), 400);
return $response;
}
if ($base64Content = $request->request->get('image')) {
$filePath = tempnam(sys_get_temp_dir(), 'UploadedFile');
$file = fopen($filePath, "w");
stream_filter_append($file, 'convert.base64-decode');
fwrite($file, $base64Content);
$meta_data = stream_get_meta_data($file);
$path = $meta_data['uri'];
fclose($file);
$entity->setFile($path);
$entity->upload();
$em->persist($entity);
$em->flush();
return new JsonResponse(array('message' => 'Success!'), 200);
}
$response = new JsonResponse(
array(
'message' => "imagem não encontrada"
), 400);
return $response;
}
these are the methods in my class
user.php
/**
* #return string
*/
public function getPictureUrl()
{
return $this->pictureUrl;
}
/**
* #param string $pictureUrl
*/
public function setPictureUrl($pictureUrl)
{
$this->pictureUrl = $pictureUrl;
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* Set file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
}
/**
* Relative path.
* Get web path to upload directory.
*
* #return string
*/
public function getUploadPath()
{
return 'uploads/pictures';
}
/**
* Absolute path.
* Get absolute path to upload directory.
*
* #return string
*/
protected function getUploadAbsolutePath()
{
return __DIR__ . '/../../../../web/' . $this->getUploadPath();
}
/**
* Relative path.
* Get web path to a cover.
*
* #return null|string
*/
public function getPictureWeb()
{
return null === $this->getPictureUrl()
? null
: $this->getUploadPath() . '/' . $this->getPictureUrl();
}
/**
* Get path on disk to a cover.
*
* #return null|string
* Absolute path.
*/
public function getPictureAbsolute()
{
return null === $this->getPictureUrl()
? null
: $this->getUploadAbsolutePath() . '/' . $this->getPictureUrl();
}
/**
* Upload a cover file.
*/
public function upload()
{
if (null === $this->getFile()) {
return;
}
$filename = $this->getFile()->getClientOriginalName();
$this->getFile()->move($this->getUploadAbsolutePath(), $filename);
$this->setPictureUrl($filename);
$this->setFile();
}
the file I get comes from the type base64, I have to turn it into a uploadfile
$file = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAA..."
I would greatly appreciate it if someone could help me to do this submition of asynchronous file.
public function submitImageAction(Request $request, $userId)
{
$this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');
$em = $this->getDoctrine()->getManager();
$entity = $this->getUser();
if ($entity->getId() != $userId) {
$response = new JsonResponse(
array(
'message' => "Não tem permissão de alterar esses dados"
), 400);
return $response;
}
if ($base64Content = $request->request->get('image')) {
$dat = preg_split("/,/", $base64Content);
if (($fileData = base64_decode($dat[1])) === false) {
$response = new JsonResponse(
array(
'message' => "Base64 decoding error."
), 400);
return $response;
}
$fileName = $entity->getUploadPath() . "/" . uniqid() . ".jpeg";
if (file_put_contents($fileName, $fileData)) {
$entity->setPictureUrl($fileName);
$em->persist($entity);
$em->flush();
return new JsonResponse(array('message' => 'Success!'), 200);
}
}
$response = new JsonResponse(
array(
'message' => "imagem não encontrada"
), 400);
return $response;
}
the error was in the driver only need to hit like sending the path to the User
I have a little problem when creating tests with PHPUnit.
Here is my setup :
protected function setUp()
{
$serviceManager = Bootstrap::getServiceManager();
$this->mockDriver = $this->getMock('Zend\Db\Adapter\Driver\DriverInterface');
$this->mockConnection = $this->getMock('Zend\Db\Adapter\Driver\ConnectionInterface');
$this->mockDriver->expects($this->any())->method('checkEnvironment')->will($this->returnValue(true));
$this->mockDriver->expects($this->any())->method('getConnection')->will($this->returnValue($this->mockConnection));
$this->mockPlatform = $this->getMock('Zend\Db\Adapter\Platform\PlatformInterface');
$this->mockStatement = $this->getMock('Zend\Db\Adapter\Driver\StatementInterface');
$this->mockDriver->expects($this->any())->method('createStatement')->will($this->returnValue($this->mockStatement));
$this->adapter = new Adapter($this->mockDriver, $this->mockPlatform);
$this->sql = new Sql($this->adapter);
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array(), array(), '', false);
$maiFormuleRevisionTable = $this->getMockBuilder('Maintenance\Model\BDD\PMaiFormulerevisionTable')
->setMethods(array())
->setConstructorArgs(array($mockTableGateway, $this->adapter, $this->sql))
->getMock();
$maiFormulerevisionService = $this->getMockBuilder('Maintenance\Service\Model\PMaiFormulerevisionService')
->setMethods(array())
->setConstructorArgs(array($maiFormuleRevisionTable))
->getMock();
$this->assertTrue($maiFormulerevisionService instanceof PMaiFormulerevisionService);
$this->controller = new RevisionsController($maiFormulerevisionService);
$this->request = new Request();
$this->routeMatch = new RouteMatch(array('controller' => 'index'));
$this->event = new MvcEvent();
$config = $serviceManager->get('Config');
$routerConfig = isset($config['router']) ? $config['router'] : array();
$router = HttpRouter::factory($routerConfig);
$this->event->setRouter($router);
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
$this->controller->setServiceLocator($serviceManager);
}
Here is the test for my function :
public function testEditFormuleActionCanBeAccessed()
{
$this->routeMatch->setParam('action', 'loadformule');
$this->routeMatch->setParam('idformule', '23');
$result = $this->controller->dispatch($this->request);
$response = $this->controller->getResponse();
$this->assertEquals(200, $response->getStatusCode());
}
And my Controler :
public function loadformuleAction()
{
try {
$iStatus = 0;
$iMaiFormuleRevisionId = (int) $this->params('idformule');
$oFormule = $this->maiFormulerevisionService->selectByIdOrCreate($iMaiFormuleRevisionId);
$maiFormulerevisionForm = new PMaiFormulerevisionForm($oFormule);
if ($this->getRequest()->isPost()) {
/* etc ... */
}
$viewModel = new ViewModel();
$viewModel->setTerminal(true);
$viewModel->setVariables([
'maiFormulerevisionForm' => $maiFormulerevisionForm,
'iMaiFormuleRevisionId' => $oFormule->getMaiFormuleRevisionId(),
'iStatus' => $iStatus
]);
return $viewModel;
} catch (\Exception $e) {
throw new \Exception($e);
}
}
But when I try to run my test, it shows an error, and I point that my test don't go into my service, when I call it ($this->maiFormulerevisionService) :
1) MaintenanceTest\Controller\RevisionsControllerTest::testEditFormuleActionCanBeAccessed
Exception: Argument 1 passed to Maintenance\Form\PMaiFormulerevisionForm::__construct() must be an instance of Maintenance\Model\PMaiFormulerevision, null given
I don't understand why my mock doesn't work ...
Thanks for your answers :)
Edit :
Hum ... when I try this :
$maiFormulerevisionService = new PMaiFormulerevisionService($maiFormuleRevisionTable);
Instead of this :
$maiFormulerevisionService = $this->getMockBuilder('Maintenance\Service\Model\PMaiFormulerevisionService')
->setMethods(array())
->setConstructorArgs(array($maiFormuleRevisionTable))
->getMock();
It goes into the service but not into the TableGateway specified in the constructor of the service ($maiFormuleRevisionTable) ... so it still doesn't work ...
You set a mock, but you also have to set what your mock returns when calling the method selectByIdOrCreate. Since you do:
$oFormule = $this->maiFormulerevisionService->selectByIdOrCreate($iMaiFormuleRevisionId);
$maiFormulerevisionForm = new PMaiFormulerevisionForm($oFormule);
The mock will return null for the selectByIdOrCreate method as long as you don't set a return value for this method.
Try to add a mock method like this:
$mock = $maiFormulerevisionService;
$methodName = 'selectByIdOrCreate';
$stub = $this->returnValue($maiFormuleRevisionTable);
$mock->expects($this->any())->method($methodName)->will($stub);
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);