I am creating a custom Registration form. On submitting the form it has to generate a mail but now it is throwing a new Exception(); error. Guide me on how to solve this problem
my code
<?php
class Huntgather_Registration_IndexController extends Mage_Core_Controller_Front_Action
{
const XML_PATH_EMAIL_RECIPIENT = 'contacts/huntgather_registration/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/huntgather_registration/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/huntgather_registration/email_template';
const XML_PATH_ENABLED = 'contacts/huntgather_registration/enabled';
public function preDispatch()
{
parent::preDispatch();
if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
$this->norouteAction();
}
}
public function indexAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('registrationForm')
->setFormAction( Mage::getUrl('*/*/post') );
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['product-name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['serial-number']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['date']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['address']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is($post['data-privacy'], 'NotEmpty')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('huntgather_registration')->__('Your registration has been processed. Thank you for registering your product'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('huntgather_registration')->__('We were unable to process your registration. Please make sure you have entered all required data in the form below'));
$this->_redirect('*/*/');
return;
}
} else {
$this->_redirect('*/*/');
}
}
}
Form submit getting error
(We were unable to process your registration. Please make sure you have entered all required data in the form below)
I think you got an exception while sending email. You should replace
Mage::getSingleton('customer/session')->addError(Mage::helper('huntgather_registration')->__('We were unable to process your registration. Please make sure you have entered all required data in the form below'));
With
Mage::getSingleton('customer/session')->addError($e->getMessage());
to get problem exactly.
Related
I have a function that loads data from a JSON file and enters it into the TYPO3 database. If I call this function via the backend Controller (indexAction), then everything works fine. However, when I call it from a task, the data is not saved. By means of test output I see that the object was changed correctly, only the Update or Add is not executed correctly, because the data in the database is not changed.
Here is my controller function:
class ImportController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
protected $siteRepository = null;
public function injectSiteRepository(SiteRepository $siteRepository)
{
$this->siteRepository = $siteRepository;
}
public function indexAction()
{
$this->dataImport();
}
public function dataImport() {
$file = "test.json";
$json = file_get_contents($file);
$jsonarray = json_decode($json);
foreach ($jsonarray->{'sites'} as $site) {
$newValue = false;
$dbSite = $this->siteRepository->getSiteByID($site->{'ID'});
if (empty($dbSite->getFirst())) {
$dbSite = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('test\test123\Domain\Model\Site');
$dbSite->setID($site->{'ID'});
$newValue = true;
} else {
$dbSite = $dbSite->getFirst();
}
//Set Data
$dbSite->setTest($site->{'TEST'});
//This object is correct, even in the Task
DebuggerUtility::var_dump(
$dbSite
);
//Update or Add new Data
if (!$newValue) {
$this->siteRepository->update($dbSite);
} else {
$this->siteRepository->add($dbSite);
}
}
$persistenceManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager');
$persistenceManager->persistAll();
return true;
}
}
Here is my task:
class JsonImportTask extends AbstractTask {
public function execute() {
$objectManager = GeneralUtility::makeInstance(
ObjectManager::class
);
$controller = $objectManager->get(ImportController::class);
$controller->dataImport();
return true;
}
}
Here my repository:
public function getSiteByID($id) {
$query = $this->createQuery();
$query->matching(
$query->equals("uid", $id),
);
return $query->execute();
}
Does anyone have an idea what this could be?
Ok I found my mistake myself. Here is the solution for all who have the same problem:
I added setRespectStoragePage in my getSiteByID function in SiteRepository:
$query->getQuerySettings()->setRespectStoragePage(false);
The error was that it was looking for the data at StoragePid 1. With this command he searches at the right place
Here is my correct repository function:
public function getSiteByID($id) {
$query = $this->createQuery();
$query->getQuerySettings()->setRespectStoragePage(false);
$query->matching(
$query->equals("uid", $id),
);
return $query->execute();
}
I had another problem. You have to set the PID number for new entries.
For example, my data is stored on Page ID 12.
I added this line here:
if (empty($dbSite->getFirst())) {
$dbSite = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('test\test123\Domain\Model\Site');
$dbSite->setID($site->{'ID'});
$newValue = true;
$dbSite->setPid(12); //New Line set PID (For me to PID 12)
} else {
$dbSite = $dbSite->getFirst();
}
I read too many questions and answers around but couldn't be sure.
I have 2 questions
1.I turned my db connection into a function and I am not sure if its
safe ?
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');
function DB()
{
try {
$pdo = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME.'', DB_USERNAME, DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
return "Error!: " . $e->getMessage();
die();
}
}
2.is my query done right way ?
query:
try {
$pdo = DB();
$stmt = $pdo->prepare("SELECT * FROM settings");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$c = htmlspecialchars($row['site_url']);
$e = filterString($row['contact']);
}
unset($stmt);
} catch (PDOException $e) {
exit($e->getMessage());
}
Thanks for any help
Perhaps keep one connection, rather than opening multiple connections to the Database. You can look into a project PDOEasy that I created to make MVC easy with PDO or use the below static example.
class DB
{
private $_connection;
private static $_instance;
public static function getInstance() {
if(self::$_instance) return self::$_instance;
self::$_instance = new self();
return self::$_instance;
}
private function __construct() {
$this->_connection = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME.'', DB_USERNAME, DB_PASSWORD, array(
PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
));
}
public function getConnection() { return $this->_connection; }
}
Which can be used like so:
$stmt = DB::getInstance()
->getConnection()
->Prepare('SELECT * FROM settings');
$stmt->execute();
foreach($stmt->fetchAll() as $row) {
// ...
}
how have I to create a custom Magento form? I don't need any extension or sample that mention the contact form. I mean that I need to understand how Magento with the modified Zend form handler works.
So the question is:
Does anybody have a code example for Magento created in a controller ?
<?php
class Mage_Contacts_IndexController extends Mage_Core_Controller_Front_Action
{
const XML_PATH_EMAIL_RECIPIENT = 'contacts/email/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/email/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/email/email_template';
const XML_PATH_ENABLED = 'contacts/contacts/enabled';
public function preDispatch()
{
parent::preDispatch();
if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
$this->norouteAction();
}
}
public function indexAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('contactForm')
->setFormAction( Mage::getUrl('*/*/post') );
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
$this->_redirect('*/*/');
return;
}
} else {
$this->_redirect('*/*/');
}
}
}
I used this tutorial: http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html
To build my first form/create user app, but it fails with an error message:
Fatal error: Call to a member function allow() on a non-object in /home/public_html/cake/app/Controller/UsersController.php on line 18
This ius the 18 line:
$this->Auth->allow('add', 'logout');
The above line is a member of function:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout');
}
My whole UsersController.php:
<?php
class UsersController extends AppController {
public function login() {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout');
}
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
public function view($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
$this->set('user', $this->User->read(null, $id));
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
unset($this->request->data['User']['password']);
}
}
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->User->delete()) {
$this->Session->setFlash(__('User deleted'));
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('User was not deleted'));
$this->redirect(array('action' => 'index'));
}
}
?>
Why does it happends?
Make sure the Auth compenent is actually called in your AppController. If you don't have an AppController create AppController.php in your Controllers directory with the following code:
<?php
class AppController extends Controller {
}
?>
The Auth component is called in a public variable in the AppController, so the controller would look like this:
<?php
class AppController extends Controller {
public $components = array('Auth');
}
?>
Auth is now available throughout your application. You could also call the AuthComponent in your UsersController, but that would make it only available to that particular controller. You probably want to use authentication in your entire application.
<?php
/**
* clmsRegistration
*
* #author MGUCS-07
* #version
*/
require_once 'Zend/Db/Table/Abstract.php';
class ClmsRegistrationModel extends Zend_Db_Table_Abstract
{
/**
* The default table name
*/
protected $_name = "clms_registration";
protected $_primary = "user_name";
public static function changePassword($username, $newpassword)
{ //changes the password
try {
$chps= new ClmsRegistrationModel();
$row = $chps->find($username);
$row1 = $row->current();
$row1->password=$newpassword;
$row1->save();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function checkUsed($username)
{ //check whether used or not
try {
$table = new ClmsRegistrationModel();
$row=$table->find($username);
if($row)
{
return 1;
}}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function deleteUser($user_name)
{ //deletes a user
try {
$deluser=new ClmsRegistrationModel();
$row = $deluser->find($user_name);
$row1=$row->current();
$result = $row1->delete();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function updateUser($user_name,$district,$email_id,$phone_number)
{
//updates the details of the user
try {
$upUser = new ClmsRegistrationModel();
$row = $upUser->find($user_name);
$row1=$row->current();
$row1->district= $district;
$row1->email_id= $email_id;
$row1->phone_number= $phone_number;
$row1->save();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function getRole($user_name)
{ //gets the role of the user
try {
$roq= new ClmsRegistrationModel();
$u= $roq->fetchRow($roq->select()->where('user_name=?',$user_name));
return $u->toArray();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public function isActive($user_name)
{ //select active user
try {
$roq = new ClmsRegistrationModel();
$u= $roq->fetchRow($roq->select()->where('user_name=?',$user_name));
return $u->toArray();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public function setActive($user_nam)
{ //sets user active
try {
$roq = new ClmsRegistrationModel();
$row= $roq->find($user_nam);
$row1=$row->current();
$row1->user_name= $user_nam;
$row1->status1 = 1;
$row1->save();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function setRole($user_name,$role)
{ //sets the role of the user
try {
$reg=new ClmsRegistrationModel();
$row = $reg->find($user_name);
$row1= $row->current();
$row1->role_organization=$role;
$row1->save();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public function register($uname,$pass,$role,$en,$status,$email,$ph,$date,$dis)
{// function for registration purposes
try{
$reg = new ClmsRegistrationModel();
$row =$reg->fetchNew();
//$row= $row->current();
$row->user_name = '$uname';
$row->password = '$pass';
$row->role = $role;
$row->employee_name=$en;
$row->status1=$status;
$row->email_id =$email;
$row->phone_number =$ph;
$row->date =$date;
$row->District=$dis;
$row->employe_id =$row->employe_id +1;
$row->save();
//$reg->save();
}
catch (Zend_Db_Exception $e){
$e->getMessage();
}
}
}
This is my model class and getting that error.
Please tell why this error and how to debug it.
well neither of those are correct answers. there are 2 braces in if statement
if($row)
{
return 1;
}}
try this
$reg = new ClmsRegistrationModel();
$row1 =$reg->createRow();
$row1->user_name = $uname;
$row1->password= $pass;
$row1->role = $role;
$row1->employee_name=$en;
$row1->status1=$status;
$row1->email_id =$email;
$row1->phone_number =$ph;
$row1->date =$date;
$row1->District=$dis;
$row1->save();
remove public from line 1 then try again