Usually on cakephp2 i used to unset form data and everything was ok.
Some times i use redirects to clear it. But i cant do that in this current page.
Anyone has found this issue or a solution for this?
If you are staying on the "add" page after successfully adding a record, for example to allow entry of multiple records more quickly, you'll need to reset the entity after saving. For example, if you're entering Posts, your controller will look something like:
$post = $this->Posts->newEntity();
if ($this->request->is('post')) {
$post = $this->Posts->patchEntity($post, $this->request->data);
if ($this->Posts->save($post)) {
$post = $this->Posts->newEntity(); // <- Reset the entity
}
}
$this->set(compact('post'));
(Error checking, flash messages, etc. all left out for brevity.)
An alternative is to simply redirect to the same page.
I had the problem that not everything was deleted
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->data)) {
$this->Flash->success(__('Submited.'));
$this->request->data(null);
$contact = new ContactForm();
return $this->redirect('/(Same Page)');// This did the final trick for me
}
}
Related
Since 3 weeks i try to learn php with the symfony framework.
I want to build an application with which i can track my expanses.
I made good progress but since 2 days i have a little logic problem so maybe someone can help me here.
I want to make a dashboard.(the main side of the project) There the user can monitor the expenditures.
This works. Now i want also a form at the dashboard, so the user can add new expenditures. I already implement a form but with a extra route. So in my ExpenditureController i have the functions dashboard and the function addExpenditure which generate different twig.html templates.
So the user can monitor his expenditures with ...budgetapp/expenditure/dashboard
and he can add new Expenditure with ...budgetapp/expenditure/addexpenditure
My Dashboard-Function
#[Route('/dashboard/', name: 'dashboard')]
public function dashboard(ExpenditureRepository $ar)
{
$user = $this->getUser();
$expenditures = $ar-> findexpendituresOfUser($user);
return $this->render('expenditure/dashboard.html.twig', [
'expenditures' => $expenditures,
]);
}
The expenditure/dashboard.html.twig shows the Expentiures of the current user in a table
My addExpenditure-Function
public function addExpenditure (ManagerRegistry $doctrine, Request $request){
$em = $doctrine->getManager();
$expenditure = new Expenditure();
$form = $this->createForm(ExpenditureType::class, $Expenditure);
$form->handleRequest($request);
if($form->isSubmitted()){
$em->persist($expenditure);
$em->flush();
}
return $this->render('expenditure/addexpenditure.html.twig', [
'addexpenditureForm' => $form->createView()
]);
}
The expenditure/addexpenditure.html.twig looks like this:
{% block body %}
<div class="container">
{{form(eintragenForm)}}
</div>
{% endblock %}
My problem /mistake in thinking:
How can i implement the form to the dashboard? So of course i can take the code from the addexpenditure function and put it 1:1 in the dashboard-funciton. but i dont think this is the right way? I also tried to including template fragments with the offical Embedding Controllers Documentation of Symfony, but this also dont work.
So someone can help me with a suggestion how you would handle this in your project?
Best regards
Markus
There are two possible solutions: put both view and add logic inside one controller's action, or separate them. Since you probably have some validation, it's reasonable to have both add and view code inside one action (otherwise, you'll have to pass errors via sessions, which is not very pretty). So basically, your dashboard/add action will look like this:
#[Route('/dashboard/', name: 'dashboard')]
public function dashboard(Request $request, ExpenditureRepository $ar, ManagerRegistry $doctrine)
{
$expenditure = new Expenditure();
$form = $this->createForm(ExpenditureType::class, $expenditure);
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $doctrine->getManager();
$em->persist($expenditure);
$em->flush();
return $this->redirectToRoute('dashboard');
}
}
$user = $this->getUser();
$expenditures = $ar-> findexpendituresOfUser($user);
return $this->render(
'expenditure/dashboard.html.twig',
[
'expenditures' => $expenditures,
'addexpenditureForm' => $form->createView(),
]
);
}
What's happening here:
First you check if POST http method was used, if it was - it means
that form has been submitted and you can handle it. There is an alternative solution without checking request method, see comments for more.
If this is a GET request, just show ordinary dashboard
If the form is submitted and it's valid - save data and redirect to
the same page. Otherwise, you'll need to empty all submitted data
from the form, etc. (it's not the right way to do it)
If the form is invalid, do not redirect, just render the page
normally, and all errors will be shown.
Finally, you of course have to render the form on your dashboard.html.twig like you did: {{form(eintragenForm)}}
I have two different Facebook leads ad campaigns (A and B) connected to the same F.B page, I've connected it to a webhook following this guide using Facebook ads PHP sdk, and pass the leads to my C.R.M, everything works fine, the problem is that I can't tell if the lead came from form A or B.
I've tried to pull the from name like this:
$input = json_decode(file_get_contents('php://input'), true);
if($input)
{
$form_id = $input['entry'][0]['changes'][0]['value']['form_id'];
$form = AdsWebhookHandler::getFormName($form_id);
}
From the AdsWebhookHandlerclass:
public static function getFormName($form_id)
{
$form = new LeadgenForm($form_id);
if(!$form) return $form_id;
return $form->read();
}
But the form always returns empty ({}) for some reason.
Does anybody know how can I pull the form name? or even better - is it possible to pass custom hidden fields in the form?
Thank you all for an answer :)
O.K so I figure out how to get the form name, all I needed to do is use the getData() function included in the Facebook PHP SDK, my code looks like this now:
public function getFormName($form_id)
{
$form = new LeadgenForm($form_id,null,$this->fb_instance);
if(!$form) return $form_id;
$data = $form->read()->getData();
return isset($data['name']) ? $data['name'] : $form_id;
}
Hope it'll help someone in the future :)
I'm doing a function that receives some form data and an Excel file which I walk and earned some data to store them in my database. So far so good, the point is that after you post, validate the Excel (good or bad this is independent of what I need) the form data is clear and I would like to keep them selected. The point is that all my code to complete all validations that I have run the following:
return $this->redirect(array('admin' => true, 'controller'=>'test', 'action'=>'test'));
I'm starting with cake and I think this may be the problem, also if I remove this code, then the data is loaded, the screen goes blank without displaying any error. It is possible, with this code, to keep the form data as they were?
You would need to store the data in the session, and then read it:
$session = $this->request->session();
$session->write('form-data', $this->request->data());
return $this->redirect(array('admin' => true, 'controller'=>'test', 'action'=>'test'));
And then in your controller:
if ($this->request->is('post')) {
$post_data = $this->request->data();
} else {
$session = $this->request->session();
$post_data = $session->consume('form-data');
}
//do stuff with $post_data
I've installed the latest version of yii2 using the advanced template. The website is working fine. For some reason the Gii generation tool is stuck and does not react as expected after clicking the preview button. Instead of showing a new form with the "Generate" button, it shows the same form unchanged without any messages as to what is happening.
Using xdebug I can see in the "actionView" method of the DefaultController that the array value $_POST['preview'] is not set, i.e. it doesn't exist in the $_POST array. I have not changed anything in the Form of the view and everything looks OK. The submit button has the name "preview" and the form is submitted but the $_POST array is not being filled with the value of the submit button. Therefore the controller does not proceed with the next steps of the generation process.
public function actionView($id)
{
$generator = $this->loadGenerator($id);
$params = ['generator' => $generator, 'id' => $id];
// ###############################################################################
// ### THIS IF STATEMENT IS NOT TRUE BECAUSE $_POST['preview'] IS NOT SET !!! ###
// ###############################################################################
if (isset($_POST['preview']) || isset($_POST['generate'])) {
// ###############################################################################
if ($generator->validate()) {
$generator->saveStickyAttributes();
$files = $generator->generate();
if (isset($_POST['generate']) && !empty($_POST['answers'])) {
$params['hasError'] = !$generator->save($files, (array) $_POST['answers'], $results);
$params['results'] = $results;
} else {
$params['files'] = $files;
$params['answers'] = isset($_POST['answers']) ? $_POST['answers'] : null;
}
}
}
return $this->render('view', $params);
}
Does anyone have an idea what could be causing this? I have a hunch that it is something quite simple that I'm overlooking, but I've never had a situation where POST variable from a Form are not being sent to the server.
False Alarm. I've found the problem. The Gii view was creating the HTML Form incorrectly.
I edit a row on the Post table or add a new row to it from edit() function in PostsController. The function looks like this:
public function edit($id = null) {
// Has any form data been POSTed?
if ($this->request->is('post')) { //Replaced 'post' by 'get' in this line
// If the form data can be validated and saved...
if ($this->Post->save($this->request->data)) {
// Set a session flash message and redirect.
$this->Session->setFlash('Updated the Post!');
return $this->redirect('/posts');
}
}
// If no form data, find the post to be edited
// and hand it to the view.
$this->set('post', $this->Post->findById($id));
}
I simply replaced 'post' by 'get' to see what would happen and it went on creating new rows without even taking me to the form. I still get the flash message 'Updated the Post!', but without taking any form data.
If the code in edit.ctp is required, here it is:
<?php
echo $this->Form->Create('Post');
echo $this->Form->input('id', array('type' => 'hidden','default'=>$post['Post' ['id']));
echo $this->Form->input('title',array('default'=>$post['Post']['title']));
echo $this->Form->input('body',array('default'=>$post['Post']['body']));
echo $this->Form->end('Update');
?>
Any thoughts on why this might be happening?
Edit: Added CakePHP Version
I am using CakePHP 2.4.5
What you are doing makes no sense.
Why would you want to switch the "post" by "get" here?
Of course it will then generate new rows, as you effectively trigger a save on each page load (GET).
Don't do that.
The code you had there was just fine - IF you also took PUT into consideration.
For edit forms, it is not a post, but:
if ($this->request->is('put')) {}
PS: If you want to make sure it always works for both add/edit, use
if ($this->request->is(array('post', 'put')) {}
But NEVER replace it with "get".