zend framework 3 tutorial - php

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...']); ?>

Related

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.

Update form Cakephp 3

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);
}

Trying to build upvote system in cakephp

I am trying to build an upvote system in cakephp but I am having some trouble and am ending up with unidentified index errors and array to string conversion.
This is my function in my PostsController:
public function like ($id=null, $like=NULL) {
if(!$id) {throw new NotFoundException(__('Invalid post'));
}
$post = $this -> Post-> findById($id);
$like = $this->Like->find('all', array(
'conditions' => array('username' =>
array($this->Auth->user('username')))
));
if(!$post) {throw new NotFoundException(__('Invalid post'));
}
$this -> set('post',$post);
$this -> set('like', $like);
if ($like['Like']['username'] == $post['Post']['username'] && $like['Like']['article_id'] == $post['Post']['id']){
$this->redirect(array('action'=>'index'));
}
else{
$this->Like->saveField('username', $this->Auth->user('username'));
$this->Like->saveField('article_id', $post);
$this->redirect(array('action'=>'index'));
}
}
At the top of my controller I do var $uses = array('Post','Like'); So my PostsController knows to use the Like model too. Now I know what problem is, I just don't know how to fix it. When I set the fields, username gets set in the DB, but $post returns an array of all posts. What I want to happen is for it to only return the current post I am on. This is what I am doing in my view:
<?php echo $this->Html->link(
'Like',
array('action'=>'Like',$post['Post']['id']));
?>
And this is the action that goes with that view:
public function view ($id=null) {
if(!$id) {throw new NotFoundException(__('Invalid post'));
}
$post = $this -> Post-> findById($id);
if(!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this -> set('post',$post);
}
How can I get my link function to only return the current post I want to like and not an array of all the posts?
EDIT - Forgot to mention I'm getting an Undefined index: Like error on the 13th line of my posts controller.
You have
$like = $this->Like->find('all', array(
'conditions' => array('username' =>
array($this->Auth->user('username')))
));
This will give an array with more items, so you cannot use $like['Like']. This is why you are getting the warning.
You could use $like[0]['Like'].
If you need to go through each of the likes, you can do
foreach ($like as $currentLike) {
if ($currentLike['Like']['username'] == $post['Post']['username'] ....
}
Please include more details about why you are making these comparisons and redirects, and maybe more of the code can be refactored.

Zend Action viewRenderer() is POST-ing my form

I am trying to send a parameter from the indexAction to the editAction using the viewRender function. The problem is when the editAction is called it causes my $form to think it has been posted.
public funciton indexAction(){
...
if(isset($_POST['edit'])){
$this->_helper->viewRenderer('edit');
$this->editAction($thingINeed);
}
...
}
public function editAction($thingINeed){
...
if($form->posted){
var_dump('FORM POSTED');
}
...
}
"FORM POSTED" is printed immediately even though I have not posted the form yet. I'm not sure why the form $form->posted is set to true on the initial render. Does anyone have an idea of why this is or a work around?
You should check your form like this:
$form = new MyForm();
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
echo 'success';
exit;
} else {
$form->populate($formData);
}
}
$this->view->form = $form;
I'm not sure about what you want to obtain, but in order to communicate value between two action, it should be better to use _getParam and _setParam method :
public funciton indexAction(){
...
if(isset($_POST['edit'])){
$this->_setParam( 'posted', true );
$this->_helper->viewRenderer('edit');
//$this->editAction($thingINeed);
// It should be better to use Action stack helper to route correctly your action :
Zend_Controller_Action_HelperBroker::getStaticHelper( 'actionStack' )->actionToStack( 'edit' );
} else {
$this->_setParam( 'posted', false );
}
...
}
// param $thingINeed is not "needed" anymore
public function editAction(){
...
if( true == $this->_getParam( 'posted' ) {
var_dump('FORM POSTED');
}
...
}

How can I redirect to the same url?

I'm trying to figure out how to make redirect to the same url after processing form in silex:
public function someAction(Application $app)
{
$form = ... // building form
if ('POST' === $app['request']->getMethod()) {
$form->bindRequest($app['request']);
if ($form->isValid())
{
$url = $app['url_generator']->generate(
$app['request']->get('_route'),
$app['request']->get('_route_params')
);
return $app->redirect($url);
}
}
return $app['twig']->render(
'form.html.twig',
array(
'form' => $form->createView()
)
);
}
It's possible in Symfony, but it's not working here. (Of course, i can always redirect to something like $url?success)
UPD: There's everything correct with $url. The point is that if you are trying to redirect to exactly the same url, it won't work.
The Request class has a getRequestUri() method. You can use that like this:
return $app->redirect($request->getRequestUri());
Sorry to answer your question with another question, but why would you want to redirect to the same page? The logic for your route should simply display your view after processing the form.
public function someAction(Application $app)
{
$form = ... // building form
if ('POST' === $app['request']->getMethod()) {
$form->bindRequest($app['request']);
if ($form->isValid())
{
$url = $app['url_generator']->generate(
$app['request']->get('_route'),
$app['request']->get('_route_params')
);
//return $app->redirect($url);
// just remove the return here and you're all set!
}
}
return $app['twig']->render(
'form.html.twig',
array(
'form' => $form->createView()
)
);
}

Categories