How to create a complete custom form - forms

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('*/*/');
}
}
}

Related

How to do queries with pdo db connection function?

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) {
// ...
}

Zend Framewok not populating all table field's value

I'm beginner for Zend Framework and using Zend Framework 2.5 veresion. I'm getting same issue and can't be resolved.My Model.php is different than show above.
Model.php
namespace User;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements AutoloaderProviderInterface, ConfigProviderInterface{
public function getAutoloaderConfig(){
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__.'/src/'.__NAMESPACE__,
)
)
);
}
public function getConfig(){
return include __DIR__. '/config/module.config.php';
}
}
My 'tbl_user' has fields with '_' like 'first_name', 'last_name', 'contact_num' which are not listing. other without underscore '_' fields are listing.
What is wrong with me, can anyone help me?
My output is:
User\Model\User Object
(
[id:protected] => 4
[first_name:protected] =>
[last_name:protected] =>
[contact_num:protected] =>
[email:protected] => dev#email.com
[designation:protected] => C++Programmer
[text:protected] =>
[name:protected] =>
[profile_pic:protected] =>
)
here is my Model 'User.php'
<?php
namespace User\Model;
class User implements UserInterface{
protected $id;
protected $first_name;
protected $last_name;
protected $contact_num;
protected $email;
protected $designation;
protected $text;
protected $name;
protected $profile_pic;
public function getId(){
return $this->id;
}
public function setId($id){
$this->id = $id;
}
public function getName(){
return $this->name;
}
public function setName($first_name, $last_name){
$this->name = $first_name.' '.$last_name;
}
public function getContact(){
return $this->contact_num;
}
public function setContact($contact_num){
$this->contact_num = $contact_num;
}
public function getEmail(){
return $this->email;
}
public function setEmail($email){
$this->email = $email;
}
public function getDesignation(){
return $this->designation;
}
public function setDesignation($designation){
$this->designation = $designation;
}
public function getProfilePic(){
return $this->profile_pic;
}
public function setProfilePic($profile_pic){
$this->profile_pic = $profile_pic;
}
/*public function getText(){
return $this->text;
}
public function setText($text){
$this->text = $text;
}*/
}
?>
and this is my 'ZendDbSqlMapper.php'
<?php
namespace User\Mapper;
use User\Model\UserInterface;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Stdlib\Hydrator\HydratorInterface;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Insert;
use Zend\Db\Sql\Update;
class ZendDbSqlMapper implements UserMapperInterface{
protected $dbAdapter;
protected $hydrator;
protected $userPrototype;
public function __construct(
AdapterInterface $dbAdapter,
HydratorInterface $hydrator,
UserInterface $userPrototype
){
$this->dbAdapter = $dbAdapter;
$this->hydrator = $hydrator;
$this->userPrototype = $userPrototype;
}
public function find($id){
$sql = new Sql($this->dbAdapter);
$select = $sql->select('tbl_users');
$select->where(array('id = ?' => $id));
$stmt = $sql->prepareStatementForSqlObject($select);
$result = $stmt->execute();
if($result instanceof ResultInterface && $result->isQueryResult() && $result->getAffectedRows()){
return $this->hydrator->hydrate($result->current(), $this->userPrototype);
}
throw new \InvalidArgumentException("User with given ID:{$id} not found");
}
public function findAll(){
$sql = new Sql($this->dbAdapter);
$select = $sql->select('tbl_users');
$stmt = $sql->prepareStatementForSqlObject($select);
$result = $stmt->execute();
//\Zend\Debug\Debug::dump($result); die;
if($result instanceof ResultInterface && $result->isQueryResult()){
//$resultSet = new ResultSet();
$resultSet = new HydratingResultSet($this->hydrator, $this->userPrototype);
//\Zend\Debug\Debug::dump($resultSet->initialize($result)); die;
return $resultSet->initialize($result);
}
return array();
}
public function save(UserInterface $userObject){
$userData = $this->hydrator->extract($userObject);
unset($userData['id']);
if($userObject->getId()){
$action = new Update('tbl_users');
$action->setData($userData);
$action->where(array('id = ?' => $userObject->getId()));
}else{
$action = new Insert('tbl_users');
$action->values($userData);
}
$sql = new Sql($this->dbAdapter);
$stmt = $sql->prepareStatementForSqlObject($action);
$result = $stmt->execute();
if($result instanceof ResultInterface){
if($newId = $result->getGeneratedValue()){
$userObject->setId($newId);
}
return $userObject;
}
return new \Exception("Database Error");
}
}
?>
here is 'ListController.php'
<?php
namespace User\Controller;
use User\Service\UserServiceInterface;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class ListController extends AbstractActionController{
protected $userService;
public function __construct(UserServiceInterface $userService){
$this->userService = $userService;
}
public function indexAction(){
return new ViewModel(array(
'users' => $this->userService->findAllUsers()
));
}
public function detailAction(){
$id = $this->params()->fromRoute('id');
try {
$user = $this->userService->findUser($id);
}catch(\InvalidArgumentException $ex){
return $this->redirect()->toRoute('user');
}
return new ViewModel(
array( 'user' =>$user )
);
}
}
?>
thank you.

In Magento, on submitting the registation form; throws a new Exception()

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.

Call to a member function allow() on a non-object - authorization

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.

Parse error: syntax error, unexpected $end, expecting T_FUNCTION in ClmsRegistrationModel.php

<?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