Symfony2 functional test to select checkboxes - symfony

I'm having trouble writing a Symfony 2 functional test to set checkboxes that are part of an array (i.e. a multiple and expanded select widget)
In the documentation the example is
$form['registration[interests]']->select(array('symfony', 'cookies'));
But it doesn't show what html that will work with and it doesn't work with mine. Here is a cutdown version of my form
<form class="proxy" action="/proxy/13/update" method="post" >
<input type="checkbox" id="niwa_pictbundle_proxytype_chronologyControls_1" name="niwa_pictbundle_proxytype[chronologyControls][]" value="1" />
<input type="checkbox" id="niwa_pictbundle_proxytype_chronologyControls_2" name="niwa_pictbundle_proxytype[chronologyControls][]" value="2" />
<input type="checkbox" id="niwa_pictbundle_proxytype_chronologyControls_3" name="niwa_pictbundle_proxytype[chronologyControls][]" value="3" />
</form>
Once it get it working there I'm going to move on to a manually made form
<input type="checkbox" id="13" name="proxyIDs[]" value="13">
<input type="checkbox" id="14" name="proxyIDs[]" value="14">
<input type="checkbox" id="15" name="proxyIDs[]" value="15">
I have tried things like
$form = $crawler->selectButton('Save')->form();
$form['niwa_pictbundle_proxytype[chronologyControls]']->select(array('3'));
$form['niwa_pictbundle_proxytype[chronologyControls][]']->select(array('3'));
but the first fails saying select is being run on a non-object and the second says Unreachable field "".

Try
$form['niwa_pictbundle_proxytype[chronologyControls]'][0]->tick();
It indexes it from 0 even in the form it says []
Or if it doesn't really helps you, you can try POSTing an array directly to the action instead of using symfony's form selectors. See: Symfony2: Test on ArrayCollection gives "Unreachable field"
Hope one of them helps you.

I think the most bulletproof solution working in 2017 is to extend your test class:
/**
* Find checkbox
*
* #param \Symfony\Component\DomCrawler\Form $form
* #param string $name Field name without trailing '[]'
* #param string $value
*/
protected function findCheckbox($form, $name, $value)
{
foreach ($form->offsetGet($name) as $field) {
$available = $field->availableOptionValues();
if (strval($value) == reset($available)) {
return $field;
}
}
}
And in the test call:
$this->findCheckbox($form, 'niwa_pictbundle_proxytype[chronologyControls]', 3)->tick();

Related

Form POST data handling with WordPress

I have hard time figuring out how to recieve form data. This is how my form looks like:
<form action="register" method="POST">
<input type="hidden" name="action" value="process_form">
<input type="email" placeholder="Enter email" name="email">
<input type="password" placeholder="Enter password" name="password">
</form>
How can I access the data of my form?
You should change your form action to something like this:
action="<?= esc_url(admin_url('admin-post.php')) ?>"
And add a hidden input in your form like this:
<input type="hidden" name="action" value="add_foobar">
And then in your backend class add an action like this:
namespace Class\Namespace;
class ClassName {
public function init() {
add_action( 'admin_post_add_foobar', [$this, 'handleForm'] );
}
public function handleForm() {
// your logic here
// use $_POST to retrieve post data
}
....
Make sure to include your class in your functions.php of your theme, like this:
(new \Class\Namespace\ClassName)->init();
To read form data, then in your handleForm method just use $_POST.
For more examples have a look at this page.
After the form has been submitted, you can access it on the page it loads with the PHP $_POST variable.
eg.
$email = $_POST['email'];
Remember to validate and sanitise this variable as it will be what the user has entered.

Missing required parameters for [Route: {$route->getName()}] [URI: {$route->uri()}]."

in new to laravel and Im trying to set up an edit blade using resource controller . ( using laravel 5.7) but it is throwing an error like this
Missing required parameters for [Route: home.hotels.update] [URI: home/hotels/{hotel}]. (View: C:\xamp\....\.....\edit.blade.php)
Please note:
when i hover over edit button it is correctly pointing to the id's and
when i tries to echo a fieldname inside my "edit function"in controller it returns the correct page but "blank" . can some one tell me wher this error comming from and if possible how to fix this
code in my index blade ( part relating to the edit)
#foreach($hotels as $c)
<tr>
<td>{{$c->hotelid}}</td>
<td>{{$c->hotelname}}</td>
<td>{{$c->city}}</td>
<td>{{$c->location}}</td>
<td>{{$c->singleroom}}</td>
<td>{{$c->doubleroom}}</td>
<td>{{$c->deluxroom}}</td>
<td>{{$c->deluxdouble}}</td>
<td>{{$c->superiorsuit}}</td>
<td><a href="{{route('home.hotels.edit',$c->id)}}"class="btn btn-info" >Update </a>
my edit blade
im passing the entries like this
<form method="post" action="{{route('home.hotels.update',$hotels->id)}}">
#csrf
{{ method_field('PUT') }}
<div class="form-group">
<div class="row">
<label class="col-md-6">Hotel ID</label>
<div class="col-md-6"><input type="text" name="hotelid" class="form-control" value="{{$hotels->hotelid}}"> </div>
</div>
......... rest of the input fields follows........
controller functions
public function index()
{
$arr['hotels']=hotels::all();
return view('admin.hotels.index')->with($arr);
}
my update function also has the same code as store ------
public function store(Request $request, hotels $hotels)
{
$hotels->hotelid=$request->hotelid;
$hotels->hotelname=$request->hotelname;
...........other fields..................
$hotels->save();
return redirect('home/hotels');
}
public function edit(hotels $hotels )
{
$arr['hotels'] = $hotels;
return view('admin.hotels.edit')->with($arr);
}
and my routes
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('home/users', 'Admin\UsersController',['as'=>'home']);
Route::resource('home/hotels', 'Admin\HotelsController',['as'=>'home']);

Can I use this Form in symfony 4?

I have added this form in twig, i need to know if this is okay and how can i recupere the input name="comments" in controller
<form action="{{ path('Update') }}" method="POST">
<input class="form-control" type="text" name="comments"
value=""></td>
<td>
<input type="submit" value="Save"/>
</form>
You can take a look at the Symfony Request Object section of the doc:
// retrieves $_GET and $_POST variables respectively
$request->query->get('id');
$request->request->get('category', 'default category');
So you can retrieve in the controller as:
$request->request->get('comments');
In your controller you can use the Request object to get all the parameters of your form, for example:
/**
* #Route("/Update")
*/
public function update(Request $request){
$comments = $request->request->get('comments');
...
}
But I recommend you to use the forms component.

Replacing entire entry-content contents in WordPress

I am developing a WordPress plugin that is inserted onto the page by adding a token to the page content.
So, on the page there is some introductory text with the contents of the plugin below. On postback, I would like to clear the introductory text and just show output from the plugin.
I know I could do this using jQuery by replacing the contents of $(".entry-content").html("plugin output"); but I wanted to ask if there was a WordPress native method of doing this instead.
UPDATE
The following is one of the files from the plugin. It is on the POST (the if condition) that I want to replace the page content, with the output of the function. On the GET (the else condition) I just want to append the output of the function to the content.
<?php
/*
The following code utilizes Heredoc syntax.
It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;).
That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon.
It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system.
This is \n on UNIX systems, including Mac OS X.
The closing delimiter must also be followed by a newline.
*/
class WHRFContactUs {
function GenerateContactUsForm() {
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$sendgrid = new SendGrid($GLOBALS['MailAPIKey']);
$email = new SendGrid\Email();
$email
->addTo($GLOBALS['MailAPISender'])
->setReplyTo($_POST['Email'])
->setFrom($GLOBALS['MailAPISender'])
->setSubject($_POST['Subject'])
->setHtml($_POST['Message'] . '<br /><hr/>' . $_POST['FullName'] . ' ' . '(' . $_POST['Email'] . ')<br/>' . '<br />')
;
try
{
$sendgrid->send($email);
$html = <<<HTML
Your message has been successfully sent. Thank you for taking the time to provide us your feedback.
<br/><br/>
In the event that your feedback requires a response, a representative will contact you as soon as possible.
HTML;
}
catch(\SendGrid\Exception $ex)
{
echo $ex->getCode();
foreach($ex->getErrors() as $er) {
echo $er;
}
}
}
else
{
$html = <<<HTML
<form method="post" id="ContactUsForm" action="{$_SERVER['REQUEST_URI']}">
<div class="form-group">
<label for="FullName" class="sr-only">Your full name</label>
<input type="text" class="form-control" id="FullName" name="FullName" placeholder="Your full name" data-validation-required="Please enter your full name.">
</div>
<div class="form-group">
<label for="Email" class="sr-only">Your email address</label>
<input type="email" class="form-control" id="Email" name="Email" placeholder="Your email address" data-validation-required="Please enter your email address." data-validation-format="Please enter a valid email address.">
</div>
<div class="form-group">
<label for="Subject" class="sr-only">Subject</label>
<input type="text" class="form-control" id="Subject" name="Subject" placeholder="Subject" data-validation-required="Please enter a subject.">
</div>
<div class="form-group">
<label for="Message" class="sr-only">Message</label>
<textarea class="form-control" id="Message" name="Message" placeholder="Your message..." data-validation-required="Please enter a message." rows="4"></textarea>
</div>
<button type="submit" id="ContactUsFormSubmit" name="ContactUsFormSubmit" class="btn btn-primary">Send message</button>
</form>
<script type="application/javascript" src="{$GLOBALS['WHRFPluginPath']}scripts/whrf-contact-us.js"></script>
HTML;
}
return $html;
}
}
add_shortcode('ContactUsForm', array('WHRFContactUs','GenerateContactUsForm'));
?>
As mentioned in the comments, without knowing how that content is being added it isn't really possible to know how to replace it.
However, there's a possibility of achieving that in a very disruptive and ill-advised way:
Chances are that content is being added by using the filter the_content.
So you could disruptively have a high-priority modification for the content and then remove that filter to stop the other content from being added. As follows:
function my_disruptive_filter($content) {
remove_all_filters('the_content');
return 'my custom content';
}
add_filter( 'the_content', 'my_disruptive_filter', -999, 1);
I'm not 100% sure if a this would work, since I've never tried it.
Also remove_all_filters takes a second parameter that's $priority which is optional. You can target all priorities that are lower that the one using with this hook, via a for loop. But I assume without providing that parameter it would just remove all of them.
Warning
The reason that this is very disruptive is that it would prevent any other code from using that filter. Another developer (or even yourself) might want to use that filter later at some point and it won't work and you have no idea why. Could be a very difficult situation to get out of.
Also this might prevent existing plugin theme from adding their content, so if you wind up using and see missing stuff -- the reason could be this.
Note: this is really a hit-or-miss solution because it depends on how that content is being added.
The function the_content() returns the page content, if you want to overwrite this using your own plugin you should remove this line in whatever page you are (usually page.php/single.php in theme dir) with your custom plugin output.

Phlacon: Getting multidimensional data from POST

If I want to get $_POST['username'] I write $this->request->getPost('username');. But how I must write to get $_POST['profile']['username']?
$this->request->getPost('profile')['username'];
To be certain to avoid invalid key errors:
$profile = $this->request->getPost('profile');
$username = isset($profile['username']) ? $profile['username'] : null;
It's important to setup your form properly. You don't use [ ] around 'profile.' The php side won't know what to do with it if you post [profile][username]. It has to be profile[username]
<input type="text" name="profile[username]" value="jsmith" />
<input type="text" name="profile[password]" value="******" />
<?php
$profile = $this->request->getPost('profile');
echo $profile['username'];
?>
Output: "jsmith"
For multidimensional you would add a key of your own to base it on.
<input type="text" name="profile[first][username]" value="jsmith" />
<input type="text" name="profile[first][password]" value="******" />
<?php
$profile = $this->request->getPost('profile');
echo $profile['first']['username'];
?>
Output: "jsmith"
This is no way. Because, I use $this->request->getPost('useremail', 'email') for checking post data.

Resources