Can't implement jroute functionality properly in joomla mvc component - php

I've made joomla 2.5 (works in joomla 3 too) component.
To test component I've created a menu item "mycomtest-main" and placed component in that menu item page. So full local testing url is "localhost/joomla/mycomtest-main".
Component lists many items and there is a button when clicked entry form is shown which is a entry form view of my that mvc component and url becomes "localhost/joomla/mycomtest-main?task=edit&id=4", as I used JRoute::_("index.php?...") to keep safe url.
So after above entry form filled and submitted, it is redirected back to default view - localhost/joomla/mycomtest-main but unfortunately url becomes - localhost/joomla/component/mycomtest-main/ instead localhost/joomla/mycomtest-main.
My component entry form view look like below -
<form action="index.php" method="post" name="adminForm" id="adminForm" enctype="multipart/form-data">
<input type="hidden" name="option" id="option" value="<?php echo $_REQUEST['option']; ?>" />
<input type="hidden" name="task" id="task" value="save" />
<input type="hidden" name="id" id="id" value="<?php if($row!=NULL){ echo $row->id; }?>" />
<input type="hidden" name="page" id="page" value="<?php echo JRequest::getVar('page'); ?>" />
.............rest of the html contents along with submit button
</form>
Also in my mvc component's controller.php file I used jroute well this way -
function save()
{
$model = $this->getModel('entry');
if($model->store())
{ $msg = "saved successfully"; $type = 'message'; }
else
{ $msg = 'error found'; $type = 'error';
}
$urlSet=JRoute::_("index.php?option=". $_REQUEST['option']."");
$this->setRedirect($urlSet, $msg, $type);
}
So how I go so that after entry view form submitted I am redirected to menu item page with
correct url below? -
http://localhost/joomla/mycomtest-main/

That is because you did not build the router for the component. you can check the router.php located inside components/com_user or write your own routing follow this one http://docs.joomla.org/Routing
or you can do like this every time you using redirect:
$menu = $app->getMenu();
$items = $menu->getItems('component', 'com_yourcom');
$itemid = JRequest::getint( 'Itemid' );
for ($i = 0, $n = count($items); $i < $n; $i++) {
// Check to see if we have found the resend menu item.
if (!empty($items[$i]->query['view']) && ($items[$i]->query['view'] == 'yourview')) {
$yourviewid = $items[$i]->id;
}
}
$redirect = JRoute::_("index.php?option=com_yourcom&Itemid=".$yourviewid ,false);
$this -> setRedirect($redirect);

Related

Zend/Php/Form - Send variable to an action function

I searched in internet for information about my problem but I found nothing. I have to send a form to php file. The problem is, I use a framework called zend and I don't understand how to send my variable to an action function from my controller. What can I put in my form action the name of my controller or the name of my function?
My form :
<form name=="downloadFile" id="downloadFile" method="POST" action=="ajaxdownloadfile()">
<input type="hidden" name="id" value="<?php $elem['evt_id']?>" />
<input type="hidden" name="nomfic" value="<?php $elem['evt_nomfic']?>" />
<input type="hidden" name="statut" value="<?php $elem['evt_statut']?>" />
<img class='js-img-download' type="submit" src='/img/download.png'>
</form>
My function action in my controller :
public function ajaxdownloadfileAction() {
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$this->view->lib = $this->_labelsFile;
$connection = ssh2_connect($this->_configFile->ftp->hostname, $this->_configFile->ftp->port);
if ($connection) {
$login = ssh2_auth_password($connection, $this->_configFile->ftp->login, $this->_configFile->ftp->password);
if ($login) {
$content = true;
if ($content) {
$id = $this->_getParam('id');
var_dump($id);
$nomfic = $this->_getParam('nomfic');
var_dump($nomfic);
$statut = $this->_getParam('statut');
echo $statut;
In ZF1 ( it is not specified but this code comes from a ZF 1.x application ) there is a standard routing where a controller/action match the www.mydomain.com/{controller}/{action}, for example www.mydomain.com/index/index.
So edit you form action
action="/yourcontroller/ajaxdownloadfile"
No double "=", no Round brackets.
IF you want to use your controller/action with ajax, just remove the 'action' attribute and create a js function that listen to the submit form event.
There are a lots of tutorial on the web

Product details not showing as intended

I found this php project on github. Vanilla Kit [https://github.com/syndicatefx/vanilla-kit] , is a very simple php powered dynamic website template, I liked the clean folder structure and hence decided to use/try it.
This is the index page on the root directory which is pretty much simple. It calls the page requested by the user (in the folder pages) and replaces the variable $page with page name requested for and displays it.
<?php
// Defualt page will always be pages/homepage.html, if not, change this to the name of the file you have created to be the homepage.
$page = 'homepage';
// Get pages based on user input
if (!empty($_GET['name'])) {
//Assign a variable to a sanitised version of the data passed in the URL
$tmp_page = basename($_GET['name']);
//If the file exists, update $page
if (file_exists("pages/{$tmp_page}.php"))
$page = $tmp_page;
//If the file does not exist, include notfound page and exit
elseif(!file_exists($tmp_page)){
include 'pages/notfound.php';
exit;
}
}
// Include $page (declared default)
include ("pages/$page.php");
?>
The default page which is the homepage fetches products from the products table and displays it.
<?php
// Edit this page's title, description and keywords for SEO
$pagetitle = 'Welcome';
$pagedescription = 'description goes here...';
$pagekeywords = 'keywords,go,here';
// Add a class to body for more CSS power
$bodyclass = 'home';
// Do Not Remove
include 'inc/header.php';
?>
<?php
$dbquery = "SELECT * FROM lbtbl_products";
$productresult = $dbconnect->query($dbquery);
if ($productresult->num_rows > 0) {
while($row = $productresult->fetch_assoc()) { ?>
<div class="prod-cnt prod-box">
<form method="post" action="cartupdate.php">
<h3 class="prod-title">
<?php echo $row["lbproductName"]; ?>
</h3>
<p><?php echo $row["lbproductDescription"];?></p>
<div class="price-cnt">
<div class="prod-price"><img src="images/common/rupees.png" width="7" height="10"/> <?php echo $row["lbproductPrice"];?></div>
Qty <input type="text" name="product_qty" value="1" size="3" />
<button class="add_to_cart">Add To Cart</button>
<input type="hidden" name="product_code" value="<?php echo $row["lbproductSku"];?>" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="<?php echo $current_url;?>" />
</div>
</form>
</div>
<?php }
} else {
echo "0 results";
}
$dbconnect->close(); ?>
<?php include 'inc/footer.php'; ?>
Everything works fine up till now.
Now, to display the product details I have a page name productdetails.php which is saved in the pages directory as all other pages. The link on the 'homepage' to view the product detail is
<?php echo $row["lbproductName"]; ?>
But once clicked a 404 not found page is displayed. But if I move the productdetails.php page to the root directory it works. Can anyone help/suggest with a solution. My best guess it has something to do with index.php code after the comment // Get pages based on user input.
Try and share the results.
<?php echo $row["lbproductName"]; ?>
And in your product detail page you should run your select query with $_GET['id'].
It may work, try and share the results.

Proper way to submit a form with php / javascript

I am trying to figure out the proper way to submit a form via php:
In part I have two questions: 1 specifically about the site that I am working on, and another about form submitting in general.
Question 1. I am using php as a template for my website. so I have one index.php page with a header and footer and all of my content is pulled in from a php function like so:
<article id="main">
<?php
$page = $_GET['page'];
if(empty($page)){
$page = 'home';
}
$page.='.php';
if(file_exists("pages/$page")) {
include("pages/$page");
} else {
echo "$page no exist";
}
?>
</article>
This is the code I am using for my form, and am using it in the head tag of my index.php page:
<head>
<?php
if ($_POST['submit'] && $human == '4') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
} else if ($_POST['submit'] && $human != '4') {
echo '<p>You answered the anti-spam question incorrectly!</p>';
}
?>
</head>
And the html form code:
<form method="post" action="index.php">
<legend>Contact Us</legend>
<fieldset>
<label>Name</label>
<input name="name" placeholder="Type Here">
<label>Email</label>
<input name="email" type="email" placeholder="Type Here">
<label>Message</label>
<textarea name="message" placeholder="Type Here"></textarea>
<label>*What is 2+2? (Anti-spam)</label>
<input name="human" placeholder="Type Here">
</fieldset>
<input id="submit" name="submit" type="submit" value="Submit">
</form>
When I submit the form it refreshes and puts my echo message into my index.php?page=home page instead of my index.php?page=contact page. How would I get the echo to stay on the same page of the form? (I have tried changing the action=" " part of the form but cant seem to get it to work).
Question 2. In general when I have been inspecting other web pages to see their form code I have been seeing this everywhere:
try
{
for(var lastpass_iter=0; lastpass_iter < document.forms.length; lastpass_iter++)
{
var lastpass_f = document.forms[lastpass_iter];
if(typeof(lastpass_f.lpsubmitorig2)=="undefined")
{
lastpass_f.lpsubmitorig2 = lastpass_f.submit;
lastpass_f.submit = function(){
var form=this;
var customEvent = document.createEvent("Event");
customEvent.initEvent("lpCustomEvent", true, true);
var d = document.getElementById("hiddenlpsubmitdiv");
for(var i = 0; i < document.forms.length; i++)
{
if(document.forms[i]==form)
{
d.innerText=i;
}
}
d.dispatchEvent(customEvent);
form.lpsubmitorig2();
}
}
}
}
catch(e){}
Is anyone familiar with the above code? And if so, is there a general script for properly submitting forms?
Thanks!
I'm not sure about your second question but for submitting the contact form, have you tried setting the action of the form to something like "index.php?page=contact"?
See how your code starts with $page = $_GET['page']; ?
It means you'll send a "page" variable as part of the url. So
change your form tag to this
<form method="GET" action="index.php?page=contact">
and you should start to see what you expect.
the method GET tells your browser to send the form data as one long URL (so, visible to the user), as opposed to POST, where data will be invisibly sent to the server (much more secure).
But then you are using $_POST to retrieve GET data, so the rest of your code won't work.
so try this instead:
go to index.php?page=contact and it will solve your first question.
Your form needs to 'remember' the current page and send it along so:
<input type='hidden' name='page' value='<?php echo $page; ?>'>
and also the script should check if current request is a form submission:
$page = (isset($_GET['page'])) ? $_GET['page'] : $_POST['page'] ;
I assume that your form is on the contact page? The page is retrieved based on a $_GET['page'] from elsewhere. When you refresh the page, it runs the page selection script again. But since you didn't come there from a form with a method=post the $_GET['page'] does not exist, hence the page is set to home as per your code. You need to store the name of the page; either as a $_SESSION variable or by a hidden input on the contact form (remember to change $_GET to $_REQUEST if you do so).

PHP $_POST strange behavior, only works 2nd time form is posted

I'm genuinely stuck on something VERY irritating. After a couple of hours of trying everything I know I've ended up here to see if anyone can help. Here's the general idea.
I want one certain page to be available with a password sent via a form. There is no user, and the password will not change. This should be easy, right!
I've got a form which submits with the method set to post, and the action set to $_SERVER['PHP_SELF']. The plan is, when the password variable I've pre-defined matches what is typed in the form, one set of content shows on the page, when it doesn't you get a different set of content (a form).
Here's what's weird. When looking at a print_r I see whatever I submit in the form in the array, but when I put the right password in the array fills, then empties quickly. I see this on the page reload. It completely empties itself. Even stranger, the 2nd time I do this, it works. What am I missing here? I'd love to know!
Many thanks, and Merry Christmas.
---- some code ----
The form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
Some PHP from the top of the file;
$pass = '12846565488374';
if($_POST['pass']){ $login = $_POST['pass']; } else { $login = 'empty'; }
if($login != $pass) { $show = 0; } elseif($login == $pass){ $show = 1; }
----- solved ------
Turns out this was a JS plugin reloading the page without me knowing.
Try:
if(isset($_POST['pass']) AND $_POST['pass'] == $pass) {
$show = 1;
} else {
$show = 0;
}
Copied from the comment below:
PHP can't update anything after the page is loaded from the server... You can only use refresh or JS/AJAX to change the content. It would be much easier if you uploaded the whole page somewhere.
Try:
<?PHP
if(isset($_POST['pass'])
{
$pass = '12846565488374';
($_POST['pass'] == $pass)? $show = 1 : $show = 0;
echo $show;
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
<?PHP
}
?>
<?php
if (isset($_POST['pass']))
{
if ($_POST['pass'] == $pass)
{
$show = 1;
echo $show;
}
else
{
$show = 0;
echo $show;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
perhaps something like this?
the purpose for the echo is to show when the correct password is entered, $show changes to 1 and when wrong, changed to 0
Edit:
Your Parameters Checking for $show
<?php
if (isset($show) AND $show === 1)
{
echo "The Variable Is Set To 1";
}
elseif (isset($show) AND $show === 0)
{
echo "The Variable Is Set To 0";
}
?>
This is tested and working with your code.
Thank you for your help everyone - as Matanya said, it was indeed a Javascript issue that was reloading the page. It's a music player and it was placed the "true" part of the IF statement. I don't understand why it has this effect, but at least I know. I thought the error would be in my PHP. Here's the player in question: SCM Music Player http://scmplayer.net
Thanks again.

Switching controllers and sending data in codeigniter

I have to devellop an internal web based application with codeigniter and I need to chain different forms (generate upon data choosen with previous form).
Right now, I tried to use form validation in the same method of the controller but the chaining only validate the first form, I tried also with $_SESSION variables but I have to send a large amount of data between each form. I tried with class variable (in controllers and models) but every time the form is send the variable are initialise...
So i wonder if there is a way to switch from a method to another one in my controller giving the data to the new controller.
my first form:
<p>Filtres: </p>
<br/><br/>
<form action="" method="post" id="form_ajout_manip" >
<label for="thematique[]">Thématique</label><br/>
<select name="thematique[]" size="20" multiple>
<?php
foreach($list_thema->result() as $thema)
{
echo "<option value='".$thema->THEMATIQUE_ID."'>".$thema->PARENT_THEMATIQUE_ID." - ".
$thema->NOM."</option>";
}
?>
</select>
<input type="hidden" value="true"/>
<br/>
<br/>
<br/>
<input type="submit" value="Rechercher" />
</form>
my second form:
<form action="" method="post" id="form_ajout_manip_cdt">
<label for="nom_manip" >Nom manipulation: </label>
<br/>
<input type="text" name="nom_manip"/>
<TABLE border="1">
<CAPTION><?php echo $data->num_rows.' '; ?>resuuultat</CAPTION>
<TR>
<?php
foreach($data->list_fields() as $titre)
{
echo '<TH>'.$titre.'</TH>';
}
?>
</TR>
<?php
foreach($data->result() as $ligne)
{
echo '<TR>';
foreach($ligne as $case)
{
echo '<TD>'.$case.'</TD>';
}
echo '<TD><input type="checkbox" name="cdt[]" value="'.$ligne->ID_CANDIDAT.'"
checked="true"</TD>';
echo '</TR>';
}
?>
</TABLE>
<br/><br/>
<input type="submit" value="créer"/>
</form>
Those are the two method of my controller
public function choix()
{
//controller for the second form
$this->info_page['title']='Ajout manipulation';
$this->load->view('ui_items/header',$this->info_page);
$this->load->view('ui_items/top_menu');
$this->load->view("manipulation/choix",$data);
}
public function filtre()
{
//controller for the first form
$this->form_validation->set_rules('thematique[]','Thematique','');
if($this->form_validation->run())
{
$data['data']=$this->manipulation_mod->select_par_filtre($this->input->post('thematique'));
//need to send $data to the second method "choix()"
}
else
{
$this->info_page['title']='Filtre ajout manipulation';
$this->load->view('ui_items/header',$this->info_page);
$this->load->view('ui_items/top_menu');
$data= array();
$data['list_op']= $this->candidat_mod->list_operateur();
$data['list_thema']= $this->thematique_mod->list_all_thematique();
$data['list_gene']= $this->candidat_mod->list_gene();
$this->load->view('manipulation/filtre', $data);
}
}
Have you any idea? I totally stuck...
Based on your clarification, let me give you an outline on what will work
View
Have both the forms in the same page
<? if(!$filtered): ?>
<input type="hidden" name="filtered" value="true"/>
/* Form 1 content here */
<? else: ?>
<input type="hidden" name="filtered" value="true"/>
/* Form 2 content here */
<? endif; ?>
Controller
You just need to use one controller
public function filter() {
$filtered = $this->input->post('filtered');
$data['filtered'] = $filtered;
if(empty($filtered)) {
/* Form validation rules for Form 1 */
/* Run form validation etc. */
/* Set title etc. for Form 1 */
} else {
/* Form validation rules for Form 2 */
/* Run form validation etc. */
/* Set title etc. for Form 2 */
}
/* Load view */
}
There might just be a better way to do this, but I am sure this will work. Good luck!

Categories