I have a search submit button, and I want my application to open another view on click. This is my code:
views/supermarkets/index.php:
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
use app\views\supermarkets\search;
?>
<h1>Supermarkets</h1>
<ul>
<p>
Search by Name
</p>
<Form Name ="form1" Method ="POST" ACTION = "app\views\supermarkets\search.php">
<INPUT TYPE = "Text" VALUE ="search by name" NAME = "searchname">
<input type="submit" value="Search">
<h3> </h3>
views/supermarkets/search.php:
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Supermarkets</h1>
<ul>
<?php
if (isset($_POST['searchname']) && $_POST['searchname']!='') {
$sname = $_POST['searchname'];
$row = Yii::app()->db->createCommand(array(
'select' => '*',
'from' => 'supermarkets',
'where' => array('like', 'Name','%'.$keyword.'')
))->queryRow();
$array = (array) $row;
}
echo $array;
function build_table($array){
// start table
$html = '<table class="altrowstable" id="alternatecolor">';
// header row
$html .= '<tr>';
foreach($array[0] as $key=>$value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
echo build_table($array);
?>
<?= LinkPager::widget(['pagination' => $pagination]) ?>
On Submit I'm getting this error:
Object not found!
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.
If you think this is a server error, please contact the webmaster.
I know there is something wrong in my code, but I just can't figure it out. And I am not sure if this is the right way to submit the POST value to my search view.
Your issue arises from this line :
<Form Name ="form1" Method ="POST" ACTION = "app\views\supermarkets\search.php">
The action must be a callable URL. Instead, you are providing a path to the view file.
Using the Yii MVC convention, you will need to generate a controller function and point the form action to that path.
In your view :
< form name ="form1" method ="POST" action="<?php Yii::createUrl('supermarket/search'); ?>" >
In your controller:
class SupermarketController extends CController
{
public function actionSearch()
{
// ... Your code here.
$this->render('another_view', array(...);
}
}
You should not use absolute path in your project. Here the list of methods I used in Yii1. Hope it will works in Yii2.
Create URL
$url = Yii::app()->createUrl('site/index', array('id'=>100));
Create URL from Controller
Yii::app()->controller->createUrl("index", array("id"=>100));
Create absolute URL
Yii::app()->createAbsoluteUrl('site/index',array('id'=>100));
Create Link
echo CHtml::link('text', array('site/index', 'id'=>100));
Redirect Browser
$this->redirect(array('site/index','id'=>100));
Remove array('id'=>100) for without values
View files inside the "protected" folder are not accessible directly by user.
crafter's answer is correct.
see here for information about controller
Related
First, forgive me if this is an overly pedantic question. I have searched trying to find answers but perhaps I'm using the wrong search terms.
Trying to use an INI file for a simple PHP application, where there is an admin page to allow application options to be easily changed. I'm able to read in the ini file with no issue, problem I'm coming across is on the write - if any boolean values are false, they won't get put into the _POST and as such don't get written back into the ini file. Here's my sample:
settings.ini file:
[Site options]
bRequireLegal['Require NDA before badge print'] = true ;
bCollectVehicleInfo['Collect vehicle information'] = false;
bShowAdditionalMessageBeforeBadgePrint['Show badge printing message'] = true;
[Company info]
companyname['Company Name'] = 'The Company, Inc.' ;
Code to read in the ini file (settings.php):
$filepath = 'settings.ini'; //location of settings file
$settings = parse_ini_file($filepath, true, $scanner_mode = INI_SCANNER_TYPED);
//pull everything in ini file in as variable
foreach($settings as $section=>$options){
foreach($options as $option=>$values){
foreach($values as $descriptor=>$value){
if(is_bool($value) === true) {
${htmlspecialchars($option)} = +$value;
}
else ${htmlspecialchars($option)} = $value;
}
}
}
And finally, the options setting page:
<?php
include 'settings.php';
//after the form submit
if($_POST){
$data = $_POST;
update_ini_file($data, $filepath);
}
function update_ini_file($data, $filepath) {
$content = "";
//parse the ini file to get the sections
foreach($data as $section=>$options){
//append the section
$content .= "[".$section."]\r\n";
//append the values
foreach($options as $option=>$values){
$content .= $option;
foreach($values as $descriptor=>$value){
$content .= "['".$descriptor."'] = '".$value."';\r\n";
}
}
$content .= "\r\n";
}
if (!$handle = fopen($filepath, 'w')) {
return false;
}
$success = fwrite($handle, $content);
fclose($handle);
return $success;
}
?>
<html>
<body>
<?php
?>
<div class="container-fluid">
<form action="" method="post">
<?php
foreach($settings as $section=>$options){
echo "<h3>$section</h3>";
//keep the section as hidden text so we can update once the form submitted
echo "<input type='hidden' value='$section' name='$section' />";
//print all other values as input fields, so can edit.
foreach($options as $option=>$values){
foreach($values as $descriptor=>$value){
if(is_bool($value) === true) {
echo "<p>".$descriptor.": <input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
} else
echo "<p>".$descriptor.": <input type='text' name='{$section}[$option][$descriptor]' value='$value' />"."</p>";
}
}
echo "<br>";
}
?>
<input type="submit" value="Update INI" />
</form>
</div>
</body>
</html>
Any help would be greatly appreciated!
In your update_ini_file() function, replace this:
$content .= "['".$descriptor."'] = '".$value."';\r\n";
with
$content .= "['".$descriptor."'] = '".($value ? 'true' : 'false')."';\r\n";
This will cause it to write the strings 'true' and 'false' instead of literal Boolean values. See How to Convert Boolean to String
Edit to add:
I think you're generating your checkboxes incorrectly:
<input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." />
This will cause the 'true' boxes to be checked, but they will still lack a value (and thus will not be transmitted to the server when the form is submitted). You should change that code to:
<input type='checkbox' name='{$section}[$option][$descriptor]' value='1'".(($value===true)?" checked":"")." />
In other words, all checkboxes should have a value of '1', but the way the browser works, only those which are checked will be submitted.
Edit to add:
Checkboxes that are not checked will not get submitted. That explains why you are not seeing any output for values that are 'false': they simply don't get submitted. When you loop through $data (which comes from $_POST), it is missing those unchecked (and thus 'false') checkboxes.
Using a solution found here: POST unchecked HTML checkboxes
Change this:
echo "<p>".$descriptor.": <input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
to this, which includes a hidden field that has the value '0', which will get submitted even if the corresponding checkbox is unchecked:
echo "<p>".$descriptor.": <input type='hidden' name='{$section}[$option][$descriptor]' value='0'><input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
However, this has its own set of potential problems, specifically when a checkbox is checked, you will send two identically named fields: one with a '0' value and the other with a '1' value. This is explained in the link above, and is left as an exercise for you to solve (or ask for further details on) if my answer doesn't work.
how to use HTML::image() for inline styled with background-image such as this html tags:
this line is into my main.blade.php file and that is main skeletion of my template.
<div style="height: 45px;background-image:url('../public/images/header_pattern2.png');border-radius: 5px;position:relative">
in main.blade.php my page view correct template. but after redirect such as login.blade.php images do not show. but after switch to index i do not have a problem.
in public directory i have images,js,css folders and my public is this:
'public' => __DIR__.'/..',
i can remove public directory. how to convert background-image:url('../public/images/header_pattern2.png'); to blade HTML::image() tag?
You may try this:
<div style="height: 45px;background-image:url('{{ asset('images/header_pattern2.png') }}');border-radius: 5px;position:relative">
Update:
Actually, HTML::image() generates an <img /> tag and you are using a div, if you want to use this using HTML::div() then you may create a custom macro.
Update: I've created this custom macro:
/**
* Param $attr : An array of styles
* Param $html : HTML content for div
* Returns HTML DIV
*/
HTML::macro('divWithBG', function($attr = array(), $html = ''){
$style = 'style = ';
foreach ($attr as $key => $value) {
if($key == 'background-image') $style .= $key.':url(\'' . $value .'\');';
else $style .= $key . ':' . $value .';';
}
return "<div $style >$html</div>";
});
You may use it in blade view as:
{{ HTML::divWithBG(array('background-image' => asset('images/8_big.jpg'), 'height' => '45px', 'border-radius'=>'5px', 'position'=>'relative' )) }}
Output:
<div style="background-image:url('http://blog.dev/images/8_big.jpg');height:45px;border-radius:5px;position:relative;"></div>
Rendered Output:
Use the following function to solve it. This is assuming that the image exist.
public function inline($path)
{
$filetype = File::type( $path );
$response = Response( File::get($path), 200 );
$response->header('Content-Type', $filetype);
return $response;
}
I tried this and it worked
background: url('{{asset('uploads/avatars/'.$employee->avatar)}}')
I would like to thank anyone who is able to help me in any way possible, I am extremely new to php/coding in general so I am not even sure if I am on the right path.
I wanted to know if it was possible to create 2 step or dynamic drop down menu using only php and html that populates the first drop down menu with folders from a directory.
So far I have
<?php
// Set the path of the dir you want displayed...
$path="./track";
$handle=opendir($path);
while ($file=readdir($handle))
{
echo "\t<option value='".$file."'>".$file."</option>\n";
}
?>
This lets me grab the the folders from a directory, how would I proceed to create a second drop down menu that would let you choose any of the files from whichever folder you selected in the first drop down menu, and then display it on the website?
An example picture of what I am trying to achieve is as follows:
http://postimg.org/image/im03tjh0d/
<?php
/**
* Check if we have submit the folder
* Check if we have submit the file
*/
$post_folder = isset($_POST['folder']) ? $_POST['folder']: null;
$post_file = isset($_POST['file_name']) ? $_POST['file_name'] : null;
/**
* Built out the Folder submission form
*/
// Set the path of the dir you want displayed...
$path="./";
echo '<form method="POST" action="', $_SERVER['PHP_SELF'],'">';
echo '<select name="folder">';
foreach (new DirectoryIterator($path) as $asset){
if($asset->isDot()) continue;
if($asset->isDir()){
/**
* If we've posted which folder we want to view the contents of
* then automatically make that selected in the dropdown on page load
*/
$selected = (isset($post_folder) && $post_folder == $asset->getFileName()) ? 'selected' : '';
echo "\t<option value='".$asset->getFilename()."' $selected>".$asset->getFilename()."</option>\n";
}
}
echo '</select>';
if(isset($post_folder)){
echo '<select name="file_name">';
$folder_to_iterate = $path.$post_folder;
foreach (new DirectoryIterator($folder_to_iterate) as $asset){
if($asset->isFile()){
/**
* If we've posted which folder we want to view the contents of
* then automatically make that selected in the dropdown on page load
*/
$selected = (isset($post_file) && $post_file == $asset->getFileName()) ? 'selected' : '';
echo "\t<option value='".$asset->getFilename()."' $selected>".$asset->getFilename()."</option>\n";
}
}
echo '</select>';
}
$btn_text = isset($post_folder) ? 'Show File Contents' : 'Show Folder Contents';
echo '<input type="submit" value="', $btn_text ,'"/>';
echo '</form>';
if(isset($post_file)){
$file_to_read = $path.$post_folder.'/'.$post_file;
echo '<pre>';
echo htmlentities(file_get_contents($file_to_read));
echo '</pre>';
}
Use ajax and the file system functions.
I'm working on a tool to replace tagged areas in a html document. I've had a look at a few php template systems, but they are not really what I am looking for, so here is what I am after as the "engine" of the system. The template itself has no php and I'm searching the file for the keyword 'editable' to set the areas that are updatable. I don't want to use a database to store anything, instead read everything from the html file itself.
It still has a few areas to fix, but most importantly, I need the part where it iterates over the array of 'editable' regions and updates the template file.
Here is test.html (template file for testing purposes):
<html>
<font class="editable">
This is editable section 1
</font>
<br><br><hr><br>
<font class="editable">
This is editable section 2
</font>
</html>
I'd like to be able the update the 'editable' sections via a set of form textareas. This still needs a bit of work, but here is as far as I've got:
<?php
function g($string,$start,$end){
preg_match_all('/' . preg_quote($start, '/') . '(.*?)'. preg_quote($end, '/').'/i', $string, $m);
$out = array();
foreach($m[1] as $key => $value){
$type = explode('::',$value);
if(sizeof($type)>1){
if(!is_array($out[$type[0]]))
$out[$type[0]] = array();
$out[$type[0]][] = $type[1];
} else {
$out[] = $value;
}
}
return $out;
};
// GET FILES IN DIR
$directory="Templates/";
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$i=0;
while ($file = readdir($dirhandler)) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$files[$i]=$file;
//echo $files[$i]."<br>";
$i++;
}
};
//echo $files[0];
?>
<div style="float:left; width:300px; height:100%; background-color:#252525; color:#cccccc;">
<form method="post" id="Form">
Choose a template:
<select>
<?php
// Dropdown of files in directory
foreach ($files as $file) {
echo "<option>".$file."</option>"; // do somemething to make this $file on selection. Refresh page and populate fields below with the editable areas of the $file html
};
?>
</select>
<br>
<hr>
Update these editable areas:<br>
<?php
$file = 'test.html'; // make this fed from form dropdown (list of files in $folder directory)
$html = file_get_contents($file);
$start = 'class="editable">';
$end = '<';
$oldText = g($html,$start,$end);
$i = 0;
foreach($oldText as $value){
echo '<textarea value="" style="width: 60px; height:20px;">'.$oldText[$i].'</textarea>'; // create a <textarea> that will update the editable area with changes
// something here
$i++;
};
// On submit, update all $oldText values in test.html with new values.
?>
<br><hr>
<input type="submit" name="save" value="Save"/>
</div>
<div style="float:left; width:300px;">
<?php include $file; // preview the file from dropdown. The editable areas should update when <textareas> are updated ?>
</div>
<div style="clear:both;"></div>
I know this answer is a little more involved, but I'd really appreciate any help.
Not sure if i correctly understand what you want to achieve. But it seems I would do that in jquery.
You can get all html elements that has the "editable" class like this :
$(".editable")
You can iterate on them with :
$(".editable").each(function(index){
alert($(this).text()); // or .html()
// etc... do your stuff
});
If you have all your data in a php array. You just need to pass it to the client using json. Use php print inside a javascript tag.
<?php
print "var phparray = " . json_encode($myphparray);
?>
I think it would be better to put the work on the client side (javascript). It will lower the server work load (PHP).
But as I said, I don't think I've grasped everything you wanted to achive.
I am trying to pass array using form post method :
submit.php
<form method="post" action="makepub.php">
<?php
.... Loop
....
echo '</td><td align="center">';
echo '<input type="checkbox" name="file_list[]" value="'.$pr.'">' ;
echo '</td><tr/>';
....
.... Loop end
?>
makepub.php :
if (isset($_POST['submit1'])) {
$file_list = $_POST["file_list"];
$how_many = count($file_list);
echo '<b>Total No of Public files chosen : </b>'.$how_many.'<br><br>';
if ($how_many>0) {
echo '<b>You changed following files to public : </b><br>';
}
for ($i=0; $i<$how_many; $i++) {
echo ($i+1) . '- ' . $file_list[$i] . '<br>';
// Some code here
}
echo "<br><br>";
}
Ok these two files works perfectly on my localhost with XAMPP.
php version 5.3
but on my server array is not getting passed.
I checked by replacing the array with single variable. Even so nothing is passed to file makepub.php
Is there anything i am missing with post here ???
Any suggestion is appreciated.
Thanks.
Your code should work as it appears, however you should make sure your submit button has a name of submit1 and then you close the form with a closing tag.