In Slim, how do I pass a GET variable to render - php

I've only been working with Slim for a short while. I'm still on version 2. So far everything has been going just fine, but I've hit a little snag. I have a page that displays content based on a GET variable at the end of the URL. The url looks like the following...
http://localhost/trailcache.com/checklist/21
The first line of the get route looks like this...
$app->get('/checklist/:Id', function($Id) use($app) {
It ends like this...
})->name('checklist');
That Id parameter controls what info I'm pulling into the page and everything has been going just fine, but now I've added a contact form and with it, some validation. I'm writing to the DB and rendering the new content okay. The problem arises when I try to send errors back to the page. Currently it looks like this...
$app->render('user/checklist.php', [
'Id' => $Id,
'errors' => $v->errors(),
'request' => $request
])->name('checklist');
This doesn't work. The page is blank. The url it returns is...
http://localhost/trailcache.com/checklist
The documentation for render shows...
$app->get('/books/:id', function ($id) use ($app) {
$app->render('myTemplate.php', array('id' => $id));
});
Wouldn't that work in the post route the same way? It has on all my other pages.
How can it get pass those errors along with the correct GET variable so that the correct content displays?

This works for me just fine.
return $this->renderer->render('myTemplate.php', array('id' => $id));
Hope it works for you.

After a few days of struggling with this, I found a solution. I first discovered map() and changed the first line to...
$app->map('/checklist/:Id', function($Id) use($app) {
and the end to...
})->via('GET', 'POST')->name('checklist');
so now the route renders the same whether it's coming from post or get. I then pointed the form to this named route...
<form action="{{ urlFor('checklist', {Id: Id}) }}" class="form" method="post">
and moved all the post logic inside this route. Since there is no need to validate if the request wasn't a post I used...
if($app->request->isPost()) {
and put the validation code inside. Refreshing the page after making a form submission would resubmit the form so if validation passed I added...
return $app->response->redirect($app->urlFor('checklist', array(
'Id' => $Id
)));
All I had to do was pass the errors to the template and it seems to be working perfectly.

Related

Laravel redirect code 302 when submit form

I faced an issue where Laravel redirects me back to my form page after submitting the form.
I was trying to return my $request data to make sure I got the correct values.
But I ended up getting redirected back to the form.
Controller:
// ServiceController.php
public function saveServiceProgress(Request $request, $id)
{
$service = Service::find($id);
$rules = $this->generateCustomRules($service);
$request->validate($rules);
$input = $request->all();
return $request;
// echo $input;
// return view('services.edit', compact('service'));
}
The form is a huge form with switch case, so I only show the form tag:
{!! Form::open(['route' => ['services.saveServiceProgress', 'id' => $service->id],'method'=>'POST', 'files'=>'true']) !!}
The form consists for dynamic input based on the id passed into the controller. It has text inputs and file inputs as well. So its a very complex form. Currently I chose the simplest version of the form to test the functionalities.
Please shed some light (and probably some code) to help me with my problems! Thanks a lot!!!
Update on route:
Route::post('services/submit/{id}', [ServiceController::class, 'saveServiceProgress'])->name('services.saveServiceProgress');
Update after fixing validator:
Managed to submit the form, now starts working on handling file upload. Thanks #Rwd and #mahmoud\ magdy for pointing out my validation issues!
use Validator::make to handle if yours validation if fails with custom errors response
see this link https://laravel.com/docs/8.x/validation#manually-creating-validators

Silverstripe form not showing error or success

I have the following form,
public function ContactForm()
{
$fields = FieldList::create(
TextField::create('Nombre', 'Tu nombre')
->setCustomValidationMessage('Por favor coloca tu nombre.')
);
$actions = FieldList::create(
FormAction::create('sendContactForm', 'Send')
);
$required = [
'Nombre',
];
$validator = new RequiredFields($required);
$form = Form::create($this, 'ContactForm', $fields, $actions, $validator);
// I'm using this novalidate for testing
$form->setAttribute('novalidate', 'novalidate');
$form->setFormMethod('POST', true);
return $form;
}
And it's not giving me errors, nor success message on submit.
If I complete the field with a string, the form submits successfully and saves my data to a model, and sends an email as well, but I get no success message.
I have another page type with another form defined the same way and it works fine, I don't know why this one doesn't show me errors.
If I leave the field empty, the sendContactForm function is not called, the page reloads with a clean form and no errors. This makes me think the validation is working correctly because it doesn't reach the submit function, but the fact the form is coming back empty even if I add data to some fields is very strange to me, because the other form comes back with the errors and with the data previously entered.
I've also tried with no JS or CSS to make sure is not a front end interference.
They are both shown in the template using $ContactForm and $MessageForm respectively.
For reference, here are some links to the full files used for both forms/pages.
Contact page
Contact page controller
Working fine form
Working fine form controller
This has been driving me nuts for hours, and I have no idea what could be wrong.

Laravel pass parameter from form to controller through (not via address line/get)?

I have a form, opening like so:
{!! Form::open(array('route' => array('admin.application.process', $questions), 'method' => 'post')) !!}
And in my controller:
public function processApplication($questions) {
...
}
My route:
Route::post('process/{questions}',
'AppController#processApplication'
);
However I want to transfer $questions in a more secure way, so members don't have any way to change it.
Currently the URL looks like this:
http://mywebsite.com/process/question_for_example
That means anyone can replace "question_for_example" and change it.
Is there any way to pass the parameter via POST to the process action in the controller, so it's hidden from the user?
Thanks!
anyting from post or get all can be catch,there is a way to make your data more secure, example :
your client and sever have a key like $saltKey = 'only myselef know string'
make encrypt string to be verify $encrypt = md5($saltkey.$questions.$clientIPOrOtheruniqueStrings)
change your route
Route::post('process/{questions}/{encrypt}',
'AppController#processApplication'
);
post data take $encrypt
on your server side verify encrypt: if (Input::get('encrypt') === md5($saltkey.Input::get('question').$clientIPOrOtheruniqueStrings)) {
}
just an example for encrypt,hope this will give you an idea

Dynamic Dropdown in yii

I followed the instructions given in the wiki in creating dynamic dropdowns in yii but still the second dropdown doesnt generate,
here is my view file:
echo CHtml::dropDownList('AccountTypeID','', array(1=>'Admin',2=>'Manager',3=>'Business',4=>'Finance',5=>'Customer Support'),array('ajax' => array('type'=>'POST',
'url'=>CController::createUrl('currentController/dynamiccities'), //url to call.
'update'=>'#city_id', //selector to update
)));
echo CHtml::dropDownList('city_id','', array());
and here is my controller:
public function actionDynamiccities(){
$data= RefAccountgroup::model()->findAll('parent_id=:parent_id',
array(':parent_id'=>(int) $_POST['AccountTypeID']));
$data=CHtml::listData($data,'AccountGroupID','AccountGroupName');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}}
Please pay attention on the 'ajax' declaration
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('currentController/dynamiccities'), //url to call.
'update'=>'#city_id', //remember to change it according to this rules #modelname_columnname
'data'=>array('AccountTypeID'=>'js:this.value'), //I think you missed this line
)));
If you have firebug installed on your firefox browser, try to look up at the console tab, and check whether your dropdownlist change successfully sent out parameter AccountTypeID and you can see the responses as well.
First things first, your question would have been improved if you actually included the link to what tutorial you tried to follow.
Second, when answering the question in the comment, "It didn't sent a data" doesn't really clarify anything. At this point, I'm not sure if you even looked in Firebug or any web developer tool to inspect what was being posted and what was being received. My guess is that if you would have looked you would have seen a POST request being made, with no data being sent, and no data being returned.
Your AJAX call doesn't have a data parameter, so $_POST['AccountTypeID'] will not be defined, meaning that $data in your controller will be empty as well.
Update your AJAX to POST the AccountTypeID, e.g.:
echo CHtml::dropDownList('AccountTypeID',
'',
array(1=>'Admin',2=>'Manager',3=>'Business',4=>'Finance',5=>'Customer Support'),
array('ajax' => array('type'=>'POST',
'url'=>CController::createUrl('currentController/dynamiccities'), //url to call.
'update'=>'#city_id', //selector to update
'data'=> '$("#AccountTypeID").serialize()',
)));
echo CHtml::dropDownList('city_id','', array());
You may need to adjust the data parameter to properly parse the correct input to get the AccountTypeID - I'm just guessing in my sample code above.
Then, while testing, make sure to use Firebug or similar to inspect what's getting POST'ed and make sure that you have AccountTypeID being passed.
Is simple. You need to declare a public variable on your model with the same name as the dropdownlist. Ex.
in your model
public mydropdown;
in your view
echo $form->dropDownList($model, 'mydropdown',array('1'=>'hello','2'=>'bye'));
Not sure if this helps, but...
echo CHtml::dropDownList('city_id','', array( 'id' => 'city_id' ));

Do query strings need to be manually sent to POST requests

This is a CakePHP / General PHP question.
In my application I use a query string like /login?continue=/admin/posts
This query string is used to redirect users to the URL in the query, but it doesn't work so it seems as though the app can't see the string...
This has got me wondering as basically when you arrive at the page with the string it's a GET request where as when you login, it becomes a POST or XML request (if using AJAX). Do I need to add the query string manually to the form for the POST to see it?
Either in the form action or a hidden input? Or am I barking up the wrong tree?
I'm currently grabbing the query like so:
if(isset($this->params['url']['continue']))
{
$pathtoredirect = $this->params['url']['continue'];
}
else
{
$pathtoredirect = $this->Auth->redirect();
}
But that's within the POST request so perhaps the query is lost... and adding it to a hidden input would not solve the problem with the current code so I would either change the code to look at the hidden field or pass the query with the action on the form?
e.g. <form action="/login?continue=/admin/posts" method="post">
Am I correct in thinking this? And would anyone be able to offer solutions or pros and cons of the two methods I mention?
In short I'm asking how to add the query string to my form action value
It currently looks like:
php echo $this->Form->create('User',
array(
'id' => 'loginform',
'type' => 'post',
'url' => array
(
'admin'=>false,
'controller' => 'users',
'action' => 'login'
)
)
);
So how would I add the query string to the form?
Thanks
When receiving a POST request you can receive both POST and GET variables through the superglobals $_POST and $_GET.
You can either send your paramater in $_GET by including it in the form's action attribute or send it in $_POST by creating an <input type="hidden"> tag within the form
A slash (/) is a reserved character. Encode it with %2F.
http://blooberry.com/indexdot/html/topics/urlencoding.htm#whatwhy
The solution was to do this:
<?php echo $this->Form->create('User',
array('id' => 'loginform', 'type' => 'post',
'url' => array('admin'=>false,'controller'=>'users','action'=>'login','url'=>$this->params['url']['continue']))); ?>
as I have a route already setup to handle the additional URL parameter:
Router::connect('/auth/login', array('controller'=>'users','action'=>'login'));
Router::connect('/auth/login?continue=:url',
array('controller'=>'users','action'=>'login'),
array(
'url' => '[A-Za-z0-9/\._-]+',
'pass' => array('url')
));
If anyone sees any issues with the way I do this though, please feel free to comment.

Categories