Form Helper default values from URL - cakephp-3.0

I have a form with method=GET.
echo $this->Form->create(NULL, array('type' => 'get'));
echo $this->Form->input('a');
echo $this->Form->input('b');
echo $this->Form->end();
But when calling formpage/?a=1&b=2 the input fields are not set with those values. Is there a way to pass $this->request->query into the form helper to set those defaults at once?

Related

Unable to open file for reading [filename.pdf] yii2 swiftmailer

I am trying to send an email with attachment when I used var_dump($filename)it returns the filename and gettype($filename) it returns string. but when I am trying to send an attachment it still returns Unable to open file for reading [filename.pdf] even if $file_attachment was looped I tried to change UploadedFile::getInstancesByName('file_attachment'); to UploadedFile::getInstanceByName('file_attachment'); but nothing happened. Please help me.
This is my controller
if(Yii::$app->request->isPost){
$email = Yii::$app->request->post('email');
$message = Yii::$app->request->post('message');
$file_attachment = UploadedFile::getInstancesByName('file_attachment');
if($file_attachment){
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message);
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach($filename);
}
//$mail->send();
//echo gettype($filename);
// var_dump($filename);
$mail->send();
}else{
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message)
->send();
}
}
This is the view
<?php
echo FileInput::widget([
'name' => 'file_attachment',
'attribute' => 'file_attachment',
'options' => ['multiple' => true]
]);
?>
The baseName property of yii\web\UploadedFile contains the original filename but the file is not present on the server under its original filename. You need to use tempName property that contains path to the uploaded file on server.
Your for each cycle that attaches files to mail should look like:
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach(
$file->tempName,
['fileName' => $filename]
);
}
It might also be a good idea to check hasError property of yii\web\UploadedFile before attempting to attach file to see if the upload was successful.
Also make sure that you've set 'enctype' => 'multipart/form-data' in you form options when you are not using ActiveForm with ActiveField::fileInput() otherwise the files might not be uploaded.

invalid json response in php when json response inside json response

i have try to print json response but "" are added to my json response
i tried below code php and id generated by drupal field
<?php
$data = array("title"=>"test","body"=>"test body");
$php = json_encode($data,JSON_FORCE_OBJECT);
echo json_encode(array("php"=>$php,"id"=>10));
?>
output :
{"php":"{\"title\":\"test\",\"body\":\"test body\"}","id":10}
but i want output like below
{"php":{"title":"test","body":"test body"},"id":10}
i added some more code for above problem
{"php":"{\"title\":\"test\",\"body\":\"test body\"}","id":10}
why not remove json_encode from echo json_encode($php);
how i can get above output` second time
You're encoding in JSON two times :
$data = array("title"=>"test","body"=>"test body");
$php = json_encode($data,JSON_FORCE_OBJECT);
echo $php ; // remove json_encode() here
After question edit:
$data = array("title"=>"test","body"=>"test body");
echo json_encode(array("php"=>$data,"id"=>10));
You can also simply do this,
<?php
$data = array("title"=>"test","body"=>"test body");
echo json_encode(array("php"=>$data,"id"=>10));
?>

Yii2 : validate if at least one checkbox is selected

I have multiple Music releases for a user for which he wants to create a promo, on the promo create form we have all the releases listed and I am using a form model for creating the promo where I define all rules for my several inputs in the promo form model.
I want to check if at-least one release is selected by the user when saving the form but it is not working as the checkboxes are created dynamically.
my form code for that field
foreach ($releaseInfo as $releases) {
if (!is_null($releases->releaseSongs)) {
echo "<fieldset><legend>" . \yii\helpers\Html::activeCheckbox($model, 'selected_releases[]', ['id' => 'release_' . $releases->id, 'onclick' => '$("#songs_' . $releases->id . '").toggle()', 'label' => false]) . " " . $releases->name . "</legend>";
foreach ($releases->releaseSongs as $k => $v) {
echo "<div id='songs_" . $releases->id . "' style='display:none'>";
echo "<div>";
echo $v->song->name;
echo "</div>";
echo "</div>";
}
}
}
echo "</fieldset>";
my rule in model
['selected_releases', 'required', 'on' => ['catalog', 'catalog_update'], 'requiredValue' => 1,
'when' => function ($model) {return ($model->scenario == self::SCENARIO_CATALOG_BASED || $model->scenario == self::SCENARIO_CATALOG_BASED_UPDATE);},
'whenClient' => 'function(attribute,value){return ("' . $this->scenario . '"=="' . self::SCENARIO_CATALOG_BASED . '" || "' . $this->scenario . '"=="' . self::SCENARIO_CATALOG_BASED_UPDATE . '")}',
'message' => 'You must select atleast one release',
]
when i submit my form the posted input variable looks like this
[selected_releases] => Array(
[0] => 0
[1] => 0
)
the requiredValue in the rule does not work because the selected_releases is an array of values it always says that
You must select atleast one release
how shoule i use the requiredValue parameter option for rules in a way that it checks for atleast one slection of the checkbox
OR
do i have to make a custom validation method an call it when validating
i used custom validation method for this purpose , my validation rule looks like following
['selected_releases', 'checkreleaseSelection'
, 'on' => ['catalog', 'catalog_update'],
'when' => function ($model) {return ($model->scenario == self::SCENARIO_CATALOG_BASED || $model->scenario == self::SCENARIO_CATALOG_BASED_UPDATE);},
'whenClient' => 'function(attribute,value){return ("' . $this->scenario . '"=="' . self::SCENARIO_CATALOG_BASED . '" || "' . $this->scenario . '"=="' . self::SCENARIO_CATALOG_BASED_UPDATE . '")}',
]
Custom method
public function checkreleaseSelection()
{
$error = true;
foreach ($this->selected_releases as $selection) {
if ($selection) {
$error = false;
}
}
if ($error) {
$this->addError('selected_releases', 'You must select atleast one of your releases to continue');
}
};

Perl CGI sending null values to mySQL database?

Scenario: I have a HTML form that sends variables to a Perl CGI which then takes them and inserts them on to a SQL DB I created earlier, but the problem is that it sends only NULL values to the DB - it does send the "correct number" of nulls though so I don't know what is going wrong. I have a feeling it is something to do with the variable passing to the Perl not Perl to DB. The Perl file:
#! \xampp\perl\bin\perl.exe -w
require "dbfunc.pl";
use warnings;
use CGI qw/:standard/;
use CGI::Carp qw(fatalsToBrowser);
$table = "routes";
#$spotted = "spotted";
$booked = "bookings";
$logged = "log";
$dbh = getConnection();
print header;
print start_html("Journey Details");
$name = param($name);
$email = param($email);
$price = param($price);
$date = param($date);
$departure = param($departure);
$arrival = param($arrival);
$adults = param($adults);
$children = param($children);
$totalCost = param($totalCost);
$departureTime = param($departureTime);
$arrivalTime = param($arrivalTime);
$jid = param($jid);
$dbh->do("INSERT INTO $logged VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", undef,
$date, $date, $name, $email, $departure, $arrival, $departureTime, $adults, $children, $totalCost);
#my $sth = $dbh->prepare(qq{INSERT INTO $logged SET DateBooked=?, Journeydate=?, Name=?, Email=?, RouteFrom=?, RouteTo=? , DepartTime=?, Adults=?, Children=?, AmountPaid=?});
#$sth->execute($date, $date, $name, $email, $departure, $arrival, $departureTime, $adults, $children, $totalCost) or die $dbh->errstr;
print end_html;
The first perl file that initially takes the vars:
#! \xampp\perl\bin\perl.exe -w
use CGI qw(:standard);
$query = new CGI;
#parameters = $query -> param;
print header, start_html("Receipt");
print p("Your Journey Receipt");
my $name = $query->param('name');
print ("Name: $name");
print br;
my $email = $query->param('email');
print ("Email: $email");
print br;
my $price = $query->param('price');
print ("Price: &pound$price");
print br;
my $date = $query->param('date');
print ("Journey date: $date");
print br;
my $departure = $query->param('departure');
print ("From: $departure");
print br;
my $arrival = $query->param('arrival');
print ("To: $arrival");
print br;
my $adults = $query->param('adults');
print ("Adults: $adults");
print br;
my $children = $query->param('children');
print ("Children: $children");
print br;
my $totalCost = $query->param('totalCost');
print ("Total Cost: &pound$totalCost");
print br;
my $departureTime = $query->param('departureTime');
print ("Departure: $departureTime");
print br;
my $arrivalTime = $query->param('arrivalTime');
print ("Arrival: $arrivalTime");
print br;
my $jid = $query->param('jid');
print ("Journey ID: $jid");
print br;
print qq!<br><form><input type="Button" value="Back" onclick="history.back()"></form>!;
print qq!<br><form method="get" action="serverside.pl">!;
print qq!<input type="submit" value="Confirm Booking" />\n</form><br />!;
print end_html;
You are misunderstanding the way CGI programs work. They don't send data to one-another: they are executed as a result of an action on a web browser, and if that action was a click on a form submit button then they will receive a set of parameters according to the names and contents of that form's <input> elements.
Your scripts don't use strict as they should, and the -w on the shebang line pretty much duplicates the action of the use warnings statement. You should use just the latter.
As Quentin says, the NULL values in the database are because you are calling $name = param($name) which, because $name is undefined, is the same as $name = param(''). You need to use a fixed string, like you did in your other script $name = param('name').
But that assumes that somewhere there is a CGI script or just an HTML file that has a <form> element with all those <input> fields. Clicking submit on such a form will execute the script specified in the action attribute and pass to it the contents of all the fields.
The first of your two scripts is expecting form input, and writes the contents of that form to the database, while the second of the two (that you say is the first perl file!) is also expecting form input but builds a web page with the information. The problem is that you don't seem to have written that form anywhere.
What I think you need is to combine the two CGI scripts, so that when submit is clicked the script both writes the information to the database and displays it on the screen. And you also need to write that form which, as I said could be just a plain HTML file.
It is also common to combine the form input and the database update in one script, which checks to see if it has been passed any parameters. If there are none then it displays the input form and waits for a response. Otherwise they are used to update the database and put up a confirmation page.
I hope this helps you.
You make the same mistake several times. I'll use the first instance an example:
$name = param($name);
You get the value of $name (which you haven't yet defined) and use it to get a param from the HTTP request. Since it isn't defined, you don't get the result you are looking for, so you don't get the submitted data in $name.
Presumably you intended:
$name = param('name');
Update now you have the form you are using:
print qq!<br><form method="get" action="serverside.pl">!;
print qq!<input type="submit" value="Confirm Booking" />\n</form><br />!;
You don't have any <input> elements except for the submit button (which doesn't have a name attribute), so there is no data to submit.

Cakephp: problems with paginator and json array as argument of the controller

I Have the controller's function "display" expecting an array encoded with JSON :
public function display($json_data){
pr($this->passedArgs);
$matches = json_decode($json_data,true);
$ids = array_keys($matches);
$this->Version->recursive = 0;
$this->Paginator->settings = $this->paginate;
$name='Versions';
$class='Version';
$items = $this->Paginator->paginate(null,array("`".$class."`.id"=>$ids));
$fields= $this->Version->schema();
$ignore=array('');
$this->set(compact('items','fields','name','class','ignore','matches'));
}
And in the display.ctp view, i have something very similar to the cookbook examples with something like:
<?php
echo '<li>'.$this->Paginator->prev('&#171', array('tag'=>'div','class' => 'pure-button prev','escape'=>false), null, array('tag'=>'div','class' => 'pure-button prev','escape'=>false)).'</li>';
echo '<li>'.$this->Paginator->numbers(array('separator' => '','class'=>'pure-button','currentClass'=>'pure-button pure-button-active')).'</li>';
echo '<li>'.$this->Paginator->next('&#187', array('tag'=>'div','class' => 'pure-button next','escape'=>false), null, array('tag'=>'div','class' => 'pure-button next','escape'=>false)).'</li>';
?>
The array '$matches' is the one who shall b eused as input argument of the controller.
And to be more precise, on the first call to "display" method, from another view than display.ctp, the array 'matches' is endcoded in JSON and the treatment is correct.
The array is kept and sent to the display.ctp view. And when I click on next or previous link of the paginator control, the array sent to the controller is worngly coded.
It seems like characters "%25" are converted into "%" where they shouldn't : it's like an html-encoding problem on the json string and making it wrong.
I get the error:
Error: The requested address /application/versions/display/%7B%223%22%3A%5B%22name%22%5D%2C%224%22%3A%5B%22name%22%5D%2C%225%22%3A%5B%22name%22%5D%2C%226%22%3A%5B%22name%22%5D%2C%227%22%3A%5B%22name%22%5D%2C%228%22%3A%5B%22name%22%5D%2C%229%22%3A%5B%22name%22%5D%2C%2210%22%3A%5B%22name%22%5D%2C%2211%22%3A%5B%22name%22%5D%2C%2212%22%3A%5B%22name%22%5D%2C%2213%22%3A%5B%22name%22%5D%2C%2214%22%3A%5B%22name%22%5D%2C%2215%22%3A%5B%22name%22%5D%2C%2216%22%3A%5B%22name%22%5D%2C%2217%22%3A%5B%22name%22%5D%2C%2218%22%3A%5B%22name%22%5D%2C%2219%22%3A%5B%22name%22%5D%2C%2220%22%3A%5B%22name%22%5D%2C%2221%22%3A%5B%22name%22%5D%2C%2222%22%3A%5B%22name%22%5D%2C%2223%22%3A%5B%22name%22%5D%2C%2224%22%3A%5B%22name%22%5D%7D/page:2' was not found on this server.
and if I look at the working string (previous to display view), i got:
http://nas/application/versions/display/%257B%25223%2522%253A%255B%2522name%2522%255D%252C%25224%2522%253A%255B%2522name%2522%255D%252C%25225%2522%253A%255B%2522name%2522%255D%252C%25226%2522%253A%255B%2522name%2522%255D%252C%25227%2522%253A%255B%2522name%2522%255D%252C%25228%2522%253A%255B%2522name%2522%255D%252C%25229%2522%253A%255B%2522name%2522%255D%252C%252210%2522%253A%255B%2522name%2522%255D%252C%252211%2522%253A%255B%2522name%2522%255D%252C%252212%2522%253A%255B%2522name%2522%255D%252C%252213%2522%253A%255B%2522name%2522%255D%252C%252214%2522%253A%255B%2522name%2522%255D%252C%252215%2522%253A%255B%2522name%2522%255D%252C%252216%2522%253A%255B%2522name%2522%255D%252C%252217%2522%253A%255B%2522name%2522%255D%252C%252218%2522%253A%255B%2522name%2522%255D%252C%252219%2522%253A%255B%2522name%2522%255D%252C%252220%2522%253A%255B%2522name%2522%255D%252C%252221%2522%253A%255B%2522name%2522%255D%252C%252222%2522%253A%255B%2522name%2522%255D%252C%252223%2522%253A%255B%2522name%2522%255D%252C%252224%2522%253A%255B%2522name%2522%255D%257D
Am I doing something wrong or missing something ?
Sam
SO, just to close the topic: I have found the answer:
I just had to re-encode the url previous to pass it to the paginator, and then to force the array as argument:
<?php
$matches_json = urlencode(json_encode($matches));
echo '<li>'.$this->Paginator->prev('&#171', array('url'=>array($matches_json),'tag'=>'div','class' => 'pure-button prev','escape'=>false), null, array('tag'=>'div','class' => 'pure-button prev','escape'=>false)).'</li>';
echo '<li>'.$this->Paginator->numbers(array('separator' => '','class'=>'pure-button','currentClass'=>'pure-button pure-button-active')).'</li>';
echo '<li>'.$this->Paginator->next('&#187', array('url'=>array($matches_json),'tag'=>'div','class' => 'pure-button next','escape'=>false), null, array('tag'=>'div','class' => 'pure-button next','escape'=>false)).'</li>';
?>