I am new to prestashop and module development. I was practicing a module which allows users to submit comment on a product. But there is an issue with form submission. I think.
Below is the code I tried.(Only methods of interest)
BulkyEdit.php
public function install()
{
if (!parent::install() )
return false;
//Registering the hook.
$this->registerHook('displayProductTabContent');
return true;
}
public function hookDisplayProductTabContent($params)
{
//Using hook displayProductTabContent.
$this->processCommentPublish();
return $this->display(__FILE__,'displayProductTabContent.tpl');
}
private function processCommentPublish()
{
$stat = Tools::isSubmit('comment_submit_form');
if($stat)
{
$stat = "submit success";
}
else $stat = "failure";
Configuration::updateValue('BULKYEDIT_TESTVAL',$stat);
}
displayProductTabContent.tpl
<form action="" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" placeholder="Tell us your name" name="name"/>
</div>
<div class="form-group">
<label for="comment">Your comment</label>
<input type="text" placeholder="Tell us your name" name="comment"/>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="comment_submit_form" value="Publish" />
</div>
</form>
$stat logs failure.
Edit : BULKYEDIT_TESTVAL logs Forms post failure
if(isset($_POST['comment_submit_form']))
{
Configuration::updateValue('BULKYEDIT_TESTVAL',$_POST);
}
else{
Configuration::updateValue('BULKYEDIT_TESTVAL','Forms post failure');
}
Any help is highly appreciated.
No Issues with the code.Everything works fine. Actually the code I wrote for the first time was different and I was using a wrong name in Tools::isSubmit('submit').But after I made changes prestashop kept using the cached files so I could not able to get the desired results according to my latest edits.
I then disabled cache and enabled Developer Mode following the instructions here.
http://blog.belvg.com/enabling-error-output-in-prestashop.html
And everything was working like a charm. So, When developing. enable Developer mode on so you can see results of your latest edits.
Related
I cannot understand why the input field "name" is not being passed to PHP. I tried commenting out the "name" code, but the same problem occurred with "company". I am setting the id and name properties on both input tags.
Revised
website example
HTML
<form name="createAccount" role="form" method="POST" action="php/AddNewAccount.php" >
<div data-toggle="buttons">
<div class="btn-group">
<label class="btn btn-primary">
<input type="radio" name="user-type" id="writer" value="writer" class="sr-only" required >Writer
</label>
<label class="btn btn-primary">
<input type="radio" name="user-type" id="enabler" value="enabler" class="sr-only" required>Enabler
</label>
</div>
</div><br/>
<div class="form-group">
<label for="name">Name:</label>
<input class="form-control" required id="name" name="name">
</div>
<div class="form-group">
<label for="company">Company:</label>
<input class="form-control" required id="company" name="company">
</div>
...
</form>
PHP
function AddNewAccount() {
try {
$acctType = $_POST["user-type"];
if (!isset($acctType) || empty(trim($acctType))) {
throw new Exception('You must select an account type."');
};
echo "account-type=" . $acctType;
$name = $_POST["name"];
if (!isset($name) || empty(trim($name))) {
throw new Exception('You must enter your name."');
};
$company = $_POST["company"];
if (!isset($company) || empty(trim($company))) {
throw new Exception('You must enter your company name."');
};
...
}
Error
[03-May-2016 21:41:44 UTC] PHP Fatal error: Uncaught exception
'Exception' with message 'You must enter your company name."' in
/home/deje/public_html/writers-tryst/php/AddNewAccount.php:18
Note the "user-type" is being passed correctly.
From what I see; your Code should work... I couldn't spot any errors, though. But, Why do you have an extra (") within your Exception Message? Are you using any Javascript on the Page? If Yes; I'd suggest you disable Javascript Temporarily and try sending the Form again without JS.
Could you try this instead?
function AddNewAccount() {
// IT MIGHT BE A GOOD IDEA (IF YOU WILL) TO DUMP THE ENTIRE $_POST GLOBAL VARIABLE
// AND END THE SCRIPT...(TEMPORARILY)... JUST TO SEE WHAT COMES BACK
// var_dump($_POST); exit; // BYPASSTHE DUMPING SINCE WE ARE SURE COMPANY MAKES IT THROUGH TO THIS POINT...
try {
$name = isset($_POST["name"]) ? htmlspecialchars(trim($_POST["name"])) : null;
$company = isset($_POST["company"]) ? htmlspecialchars(trim($_POST["company"])) : null;
$acctType = isset($_POST["user-type"]) ? htmlspecialchars(trim($_POST["user-type"])) : null;
if (!$acctType) {
throw new Exception('You must select an account type.');
}
if (!$name) {
throw new Exception('You must enter your name.');
}
if (!$company) {
throw new Exception('You must enter your company name.');
}
...
}
This the Result from the var_dump($_POST) on your App.
As you can see, Your code is still consistent and you now have the Company in the list of your Data.... so you may want to comment out the var_dump(); exit; part
<?php
//....PREVIOUS CODE
// var_dump($_POST); exit; //NOW COMMENTED OUT TO CONTINUE WITH THE PROGRAM
Try this and let's know how it goes...
I sincerely hope it goes well with you Now, though ;-)
Try the following:
<form name="createAccount" role="form" method="POST" action="php/AddNewAccount.php" enctype="application/x-www-form-urlencoded">
You can also parse it as a JSON:
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
Believe it or not, the problem was with the input tags ending in ">" instead of "/>". I have been testing in Chrome. I tested in IE now and it works there too. Thanks for everyone's input.
I'm quite new to PHP but used to some other programming languages (e.g JAVA,Python). Recently I had a closer look to the Login-Script panique/php-login-advanced (https://github.com/panique/php-login-advanced) which I find is a really good way to learn some useful PHP-structures.
Unfortunately there is one thing, i don't understand and which gives me quite a headache: all starts from "index.php" whih includes "login_manager.php" (used, among others, to create a new Login-instance from "classes/Login.php").
// create a login object. when this object is created, it will do all login/logout stuff automatically
// so this single line handles the entire login process.
$login = new Login();
If you aren't logged in, you can register yourself, which leads you to "views/register.php". In this file there is a POST-form, calling the same file again:
<?php include('_header.php'); ?>
<!-- show registration form, but only if we didn't submit already -->
<?php if (!$registration->registration_successful && !$registration->verification_successful) { ?>
<form method="post" action="register.php" name="registerform">
<label for="user_name"><?php echo WORDING_REGISTRATION_USERNAME; ?></label>
<input id="user_name" type="text" pattern="[a-zA-Z0-9]{2,64}" name="user_name" required />
<label for="user_email"><?php echo WORDING_REGISTRATION_EMAIL; ?></label>
<input id="user_email" type="email" name="user_email" required />
<label for="user_password_new"><?php echo WORDING_REGISTRATION_PASSWORD; ?></label>
<input id="user_password_new" type="password" name="user_password_new" pattern=".{6,}" required autocomplete="off" />
<label for="user_password_repeat"><?php echo WORDING_REGISTRATION_PASSWORD_REPEAT; ?></label>
<input id="user_password_repeat" type="password" name="user_password_repeat" pattern=".{6,}" required autocomplete="off" />
<img src="tools/showCaptcha.php" alt="captcha" />
<label><?php echo WORDING_REGISTRATION_CAPTCHA; ?></label>
<input type="text" name="captcha" required />
<input type="submit" name="register" value="<?php echo WORDING_REGISTER; ?>" />
</form>
<?php } ?>
<?php echo WORDING_BACK_TO_LOGIN; ?>
<?php include('_footer.php'); ?>
Now I don't understand where this $registration instance comes from?! Of course it should be an instance of "classes/Registration.php" which explains the further processing using the constructor of the class:
public function __construct()
{
session_start();
// if we have such a POST request, call the registerNewUser() method
if (isset($_POST["register"])) {
$this->registerNewUser($_POST['user_name'], $_POST['user_email'], $_POST['user_password_new'], $_POST['user_password_repeat'], $_POST["captcha"]);
// if we have such a GET request, call the verifyNewUser() method
} else if (isset($_GET["id"]) && isset($_GET["verification_code"])) {
$this->verifyNewUser($_GET["id"], $_GET["verification_code"]);
}
}
But where is the connection here? I searched the complete project with all files and I could not find something like "new Registration()" and even the $registration variable is never set (to my knowledge). So as the script works without problems, there needs to be some trick i don't know.
I also thought it could be set in the "_header.php" but in this file there is only some error-output:
// show potential errors / feedback (from registration object)
if (isset($registration)) {
if ($registration->errors) {
foreach ($registration->errors as $error) {
echo $error;
}
}
if ($registration->messages) {
foreach ($registration->messages as $message) {
echo $message;
}
}
}
I am new with php, but I have already made a registration script that works fine. But the problem is every time I press the submit button to check my error, I'm going to a new page.
My question is how I make that error comes on the same page?
The code I am useing for the html form.
I want the error display in the error div box that I made Any idea ?
<div id="RegistrationFormLayout">
<h1>Registration Page</h1>
<div id="ErrorMessage"></div>
<form action="script/registration.php" method="post">
<label for="Username">Username</label>
<input type="text" name="Regi_username">
<label for="FirstName">FirstName</label>
<input type="text" name="Regi_Firstname">
<label for="LastName">LastName</label>
<input type="text" name="Regi_Lastname">
<label for="EamilAddress">Regi_EmailAddres</label>
<input type="text" name="Regi_EmailAddres">
<label for="Password">Password</label>
<input type="password" name="Regi_password">
<button type="submit" value="Submit" class="Login_button">Login</button>
</form>
</div>
If I understand correctly, you want form validation errors there. This is a very common pattern, and the simple solution is to always set a form's action attribute to the same page that displays the form. This allows you to do the form processing before trying to display the form (if there are $_POST values). If the validation is successful, send a redirect header to the "next step" page (with header()).
The basic pattern looks like this (in very very simplified PHP)
<?php
if(count($_POST)) {
$errors = array();
$username = trim($_POST['Regi_username']);
if(empty($username)) {
$errors[] = 'username is required';
}
if(count($errors) == 0) {
header('Location: success.php');
die();
}
}
<ul class="errors">
<?php foreach($errors as $error) { ?>
<li><?php echo $error;?></li>
<?php } ?>
</ul>
I want to allow people to submit their contacts by entering it into a field and it would eventually send it to the database but been trying it for quite some time and cant find out whats wrong with it, if possible do let me know how to return a echo saying "SENT" when its in database. Redirecting to the same page, if possible , dont even need a refresh to get that SENT shown to people.
This is my Controller
$this->config->db_config_fetch();
$this->load->model('skills_model');
//Get Form Data
$this->input->post('submitsms') ;
//GEt phone number from field
$type = $this->input->post('phonenumber');
//Call model
$this->skills_model->addsms($type);
}
This is my View # home page
<form method="post" action="<?php echo site_url(''); ?>" name="form" enctype="multipart/form-data">
<label>SMS Subscription</label>
<input type="text" name="phonenumber" placeholder="Phone Number here">
<button class="btn btn-info" name="submitsms" type="submit">Subscribe</button>
</form>
This is my Model
function addsms($type){
$this->db->set('number', $type);
$this->db->insert('subscribers');
}
I also tried the following
function addsms($type){
$sql = "INSERT INTO 'subscribers' ('number') VALUES ($type)";
$this->db->query($sql);
echo $this->db->affected_rows();
}
You advice would be of a great help! thank you!
A small example ...........
View file
<form action="<?php echo ROOT_FOLDER ?>/add_price" method="post">
<input type="text" class="text" name="amount" value="<?php echo set_value('amount'); ?>" />
<input type="submit" class="submit" value="Approve" />
</form>
Controller...........
public function post_add_price()
{
$data = array(
'amount'=>$this->input->post('amount'),
);
$this->model->add_amount($data); //sending amount to model to insert in dataabse
echo "Amount added to database";
}
Model................
public function add_amount($data)
{
$this->insert_helper('order_amount_table',$data);
}
public function insert_helper($table_name, $data_array){
$this->db->insert($table_name,$data_array);
return $this->db->insert_id();
}
I hope this example will help you .........if you have any doubts ask
is there any server side form validation in magento? i have created a from and using magentos form validation but its not gonna work if someone disable the javascipt and enters something that can be harmful. if there is no built in class for that. could someone please point me in a direction how to implement a server side form validation as a backup. here is my my code for the form
<div style="border:0px solid red; margin:0px auto;">
<?php $_product = $this->getProduct(); ?>
<form id="test" action="<?php echo Mage::getUrl('pricenotify/pricenotify/db') ?>" method="post">
<label for="price">Price *</label>
<input type="text" id="price" name="price" value="" class="required-entry validate-number"/><br />
<label for="email">Email Address *</label>
<input type="text" id="email" name="email" value="" class="required-entry validate-email"/>
<input type="hidden" id="id" name="id" value="<?php echo $_product->getId() ?>" />
<input type="hidden" id="propri" name="propri" value="<?php echo $_product->getPrice() ?>" />
<input type="submit" name="submit" value="<?php echo $this->__('Submit') ?>" onclick="if(customForm.validator && customForm.validator.validate()) this.form.request(); return false;" />
</form>
<script type="text/javascript">
//< ![CDATA[
var customForm = new VarienForm('test',false);
//]]>
</script>
If you want to keep it simple, you could do the validation in your controller
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is($postObject->getPrice(), 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is($postObject->getEmail(), 'EmailAddress')) {
$error = true;
}
if ($error) {
throw new Exception();
}
//save to db
return;
} catch (Exception $e) {
Mage::getSingleton('customer/session')->addError(Mage::helper('pricenotify')->__('Unable to submit your request. Please, try again later'));
$this->_redirect('/');
return;
}
Zend_Validate : http://files.zend.com/help/Zend-Framework/zend.validate.html
Yes, Magento has server-side validation for some forms. However, the module that added the form is responsible for validating it - so if you're dealing with third-party code like a plugin, it might not be there.
Conventionally, the validation code lives with the Model part of a module. For example, in Magento's built-in review functionality, when a review form is submitted, its data is validated by the validate() function in the /app/code/core/Mage/Review/Model/Review.php file. I'd start by looking at that code, and the code in existing Mage/Core modules for examples.
In the situation that you give, the conventional place for the validation logic would be /app/code/local/YourCompany/PriceNotify/Model/Pricenotify.php
Magento uses prototype to validate forms. To implement this validation, just add "required-entry" to your input tag.