Update form Cakephp 3 - php

I am currently working on a project using cakephp 3.
I have a form to add clients which works using this in my controller :
public function add(){
$clients = $this->Clients->newEntity();
if($this->request->is('post')){
$clients = $this->Clients->patchEntity($clients, $this->request->data);
if($this->Clients->save($clients)){
$this->Flash->success(__('Client has been created.'));
return $this->redirect(['controller'=>'Clients','action'=>'index']);
}
$this->Flash->error(__('Client hasnt been created.'));
}
$this->set('clients',$clients);
}
Then I want to have the possibility to modify one of my client.
I have a table of clients and when I click on of them, I have a modify button coming (jQuery).
Then I'm on my modify page. I did some test with the doc from cake but it seems I don't understand how it works and what tools should I use.
For the moment, I have this on my Controller:
public function modify($id = null){
if(empty($id)){
throw new NotFoundException;
}
$clients = $this->Clients->get($id);
/* there should be the modify code */
$this->set('clients', $clients);
}
I don't really know what to use as I said... Any help pls?

The code for editing a record is quite straight forward:
public function modify($id = null){
if(empty($id)){
throw new NotFoundException;
}
$client = $this->Clients->get($id);
if ($this->request->is(['post', 'put']) {
$client = $this->Clients->patchEntity($client, $this->request->data);
if ($this->Clients->save($client)) {
return $this->redirect($someURL);
}
}
$this->set('client', $client);
}

Related

Add favorite with symfony

I am learning symfony.
I try to save favorite when I click on a link and when I click again on the link, I wish I could remove the favorite in DB.
When clicking, I do have a new row in my database.
If I click again, it add a new one and don't erase the row.
This is what i have done in my controller:
public function addFavorite(EntityManagerInterface $manager, PostRepository $postRepository, Post $post)
{
$favorite = $postRepository->findOneBy(['content' => $post,'author' => $this->getUser()
]);
if (is_null($favorite)) {
$favorite = new Favorite();
$favorite
->setPost($post)
->setUser($this->getUser());
$manager->persist($favorite);
$manager->flush();
return $this->render('favorite/index.html.twig');
} else {
$manager->remove($favorite);
$manager->flush();
return $this->render('favorite/index.html.twig');
}
}
From what i understand, the problem is that $favorite is still NULL and i don't understand why...
If someone could help me, thanks !
I think it's because you don't request the good entity. I don't really know your entities, but I think this could be more logical :
public function addFavorite(EntityManagerInterface $manager, FavoriteRepository $favoriteRepository, Post $post)
{
$favorite = $favoriteRepository->findOneBy([
'post' => $post,
'user' => $this->getUser()
]);
if (!$favorite) {
$favorite = new Favorite();
$favorite
->setPost($post)
->setUser($this->getUser());
$manager->persist($favorite);
} else {
$manager->remove($favorite);
}
$manager->flush();
return $this->render('favorite/index.html.twig');
}

cakephp 3.x updating user data

I have written a basic login script and now need to update the data stored in the auth component and then save it to the database, this is what i have so far;
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$this->Auth->user()->last_activity = date("Y-m-d");
$this->Users->save($this->Auth->user());
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Email or password is incorrect, please try again.'));
}
}
I've tried a few different variations but can't get any to work. Any ideas?
Updating data in cakephp3 is slightly different than cakephp2, Try something like this:
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$userData = $this->Users->get($user['id']);
$userData->last_activity = date("Y-m-d");
if($this->Users->save($userData)){
$user['last_activity'] = $userData->last_activity; // to update auth component
}
// echo $this->Auth->user('last_activity');
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Email or password is incorrect, please try again.'));
}
}
Another way of updating record in cakephp3 is:
$query = $this->Users->query();
$query->update()
->set(['last_activity ' => date('Y-m-d')])
->where(['id' => $user['id']])
->execute();
But I don't recommend this one as callbacks are not fired.
In Cake3, you can take advantage of the afterIdentify event.
In AppController::initialize, add a listener for the event:
\Cake\Event\EventManager::instance()->on('Auth.afterIdentify', [$this, 'afterIdentify']);
Add AppController::afterIdentify function to handle the event:
public function afterIdentify(CakeEvent $cakeEvent, $data, $auth) {
$users_table = TableRegistry::get('Users');
$user = $users_table->get($data['id']);
$user->last_activity = new Cake\I18n\FrozenTime();
// If you ever need to do password rehashing, here's where it goes
if ($this->Auth->authenticationProvider()->needsPasswordRehash()) {
$user->password = $this->request->data('password');
}
$users_table->save($user);
}
Now, the data returned by the Auth->user() call should always be up-to-date without any extra effort on your part.

zend framework 3 tutorial

I am trying a Zend framework 3 tutorial and am getting stuck in "editing" a function in the in-depth part (Blog case).
When trying to edit a blog message, the editing form doesn't show the original message. It seems that the original message couldn't be bound to the form.
I copied all the sample code. I don't know what is wrong with it. By the way, my add and delete function work fine.
can anyone help me with it?
The editAction method from the tutorial:
public function editAction()
{
$id = $this->params()->fromRoute('id');
if (! $id) {
return $this->redirect()->toRoute('blog');
}
try {
$post = $this->repository->findPost($id);
} catch (InvalidArgumentException $ex) {
return $this->redirect()->toRoute('blog');
}
$this->form->bind($post);
$viewModel = new ViewModel(['form' => $this->form]);
$request = $this->getRequest();
if (! $request->isPost()) {
return $viewModel;
}
$this->form->setData($request->getPost());
if (! $this->form->isValid()) {
return $viewModel;
}
$post = $this->command->updatePost($post);
return $this->redirect()->toRoute(
'blog/detail',
['id' => $post->getId()]
);
}
Edit this code:
if (! $request->isPost()) {
foreach($this->form->getMessages() as $message){
$this->flashMessenger()->addErrorMessage($message['message']);
}
}
In your view:
<?php echo $this->flashMessenger()->renderCurrent('error', ['options go here...']); ?>

Laravel Multiple Form Request Validation

I have products and software and movie belongs to product. I have created two validation requests and want to validate them like shown below.
public function store(StoreProductRequest $old_request)
{
if ($old_request->type == 'MOVIE')
$request = new StoreMovieRequest;
else
$request = new StoreSoftwareRequest;
$request = $old_request;
$request->validate();
}
Is there any way to achieve this in Laravel 5.1? I hope you understand my question.
One way of doing what you want to achieve is
public function store(StoreProductRequest $old_request){
if ($old_request->type == 'MOVIE'){
$request = new Requests\StoreMovieRequest;
$this->validate($old_request, $request->rules());
//validation passed for StoreMovieRequest
}
else {
$request = new Requests\StoreSoftwareRequest;
$this->validate($old_request, $request->rules());
//validation passed for StoreSoftwareRequest
}
}

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.

Categories