zend framework stringtrim filter not working - zend-framework

I'm having trouble with zend framework's string trim filter. I use the following code to set up a text element in a Zend_Form:
$voucherValidator = new Project_Validate_Voucher();
$code = $this->addElement('text', 'code', array('label'=>'Gutscheincode'));
$code = $this->getElement('code')
->addFilter('StringTrim')
->addValidator($voucherValidator, true);
When I type in some text with preceeding blanks or tabs, the validator correctly works on the StringTrim filtered input and accepts the input. When I later check the $_POST['code'] after code submission, I get the unfiltered input. How can I get my text element to post the filtered value?

Use $code = $this->code->getValue() as Zend_Form doesn't actually filter the $_POST array.

Sorry, i know i'm late but in case any one faced the same problem,
I have faced this problem today and i found few ways to solve this problem:
i have answered same reply on this post
Other Post
first my code is:
This is the form class
class Application_Form_UserForm extends Zend_Form
{
public function init()
{
/* Form Elements & Other Definitions Here ... */
$this->setMethod('POST');
$fname = new Zend_Form_Element_Text('fname');
$fname->setLabel('First Name: ');
$fname->setAttribs(Array(
'placeholder'=>'Example: Eslam',
'class'=>'form-control'
));
$fname->setRequired();
$fname->addValidator('StringLength', false, Array(4,20));
$fname->addFilter('StringTrim');
$fname->addFilter('StripTags');
$fname->removeDecorator('DtDdWrapper');
$fname->removeDecorator('label');
$fname->removeDecorator('HtmlTag');
$lname = new Zend_Form_Element_Text('lname');
$lname->setLabel('Last Name: ');
$lname->setAttribs(Array(
'placeholder'=>'Example: Khoga',
'class'=>'form-control'
));
$lname->setRequired();
$lname->addValidator('StringLength', false, Array(4,20));
$lname->addFilter('StringTrim');
$lname->addFilter('StripTags');
$lname->removeDecorator('DtDdWrapper');
$lname->removeDecorator('label');
$lname->removeDecorator('HtmlTag');
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email: ');
$email->setAttribs(Array(
'placeholder'=>'Example#Example.com',
'class'=>'form-control'
));
$email->setRequired();
$email->addValidator('StringLength', false, Array(5,250));
$email->addFilter('StringTrim');
$email->addFilter('StripTags');
$email->removeDecorator('DtDdWrapper');
$email->removeDecorator('label');
$email->removeDecorator('HtmlTag');
$gender = new Zend_Form_Element_Select('gender');
$gender->setRequired();
$gender->addMultiOption('male','Male')->
addMultiOption('female','Female')->
addMultiOption('none','Prefer not to mention');
$gender->setAttrib('class', 'form-control');
$track_obj = new Application_Model_Track();
$allTracks = $track_obj->listAll();
$track = new Zend_Form_element_Select('track');
foreach($allTracks as $key=>$value)
{
$track->addMultiOption($value['id'], $value['name']);
}
$submit= new Zend_Form_Element_Submit('submit');
$submit->setAttribs(array('class'=>'btn btn-success'));
$reset= new Zend_Form_Element_Submit('reset');
$reset->setAttribs(array('class'=>'btn btn-danger'));
$this->addElements(array(
$fname,
$lname,
$email,
$gender,
$track,
$submit,
$reset
));
}
}
This is controller class
class UserController extends Zend_Controller_Action{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
public function listAction()
{
// action body
$user_model = new Application_Model_User();
$this->view->users = $user_model->listUsers();
$track_form = new Application_Form_Track();
$this->view->track_form = $track_form;
$track_model = new Application_Model_Track();
$request = $this->getRequest();
if($request->isPost())
{
if($track_form->isValid($request->getPost())){
$track_model-> addTrack($request->getParams());
$this->redirect('/user/add');
}
}
}
public function detailsAction()
{
// action body
$user_model = new Application_Model_User();
$us_id = $this->_request->getParam("uid");
$user = $user_model->userDetails($us_id);
$trackModel = new Application_Model_Track();
$track = $trackModel->getTrackName($user[0]['track']);
$user[0]['track'] = $track[0]['name'];
$this->view->user = $user[0];
}
public function deleteAction()
{
// action body
$user_model = new Application_Model_User();
$us_id = $this->_request->getParam("uid");
$user_model->deleteUser($us_id);
$this->redirect("/user/list");
}
public function addAction()
{
// action body
$form = new Application_Form_UserForm();
$request = $this->getRequest();
if($request->isPost()){
if($form->isValid($request->getPost())){
/*echo "<pre>";
print_r($form);
echo "</pre>";
exit;*/
$userData['fname'] = $form->getValue('fname');
$userData['lname'] = $form->getValue('lname');
$userData['email'] = $form->getValue('email');
$userData['gender'] = $form->getValue('gender');
$userData['track'] = $form->getValue('track');
$user_model = new Application_Model_User();
$user_model-> addNewUser($userData);
$this->redirect('/user/list');
}
}
$this->view->user_form = $form;
}
public function editAction()
{
// action body
$form = new Application_Form_UserForm();
$user_model = new Application_Model_User ();
$id = $this->_request->getParam('uid');
$user_data = $user_model-> userDetails($id)[0];
$form->populate($user_data);
$this->view->userName = $user_data['fname']." ".$user_data['lname'];
$this->view->user_form = $form;
$request = $this->getRequest();
if($request->isPost()){
if($form->isValid($request->getPost())){
$userData['fname'] = $form->getValue('fname');
$userData['lname'] = $form->getValue('lname');
$userData['email'] = $form->getValue('email');
$userData['gender'] = $form->getValue('gender');
$userData['track'] = $form->getValue('track');
$user_model-> updateUser($id, $userData);
$this->redirect('/user/list');
}
}
}
}
First Solution:
i used filter on Form elements in the form class,
but i retrieved data from $form object in the controller,
as i found that method
addFilter()
doesn't change in the $_POST array values, so i have retrieved the data from $form object and then passed it as array to Model.
Second Solution:
i have tried to apply the filter on the values in the controller, not in the form by creating object from filter class and apply needed filter
Third Solution:
is to use method
addValidator()
with regex which affects on $_POST values.

Related

Magento 2.4: create CSV File for each order placed

I am new to magento. I need to automatically create a csv file whenever an order is placed by the customer.
I am using the event "sales_order_place_after" but the code in the observer is not working.
Can anyone guide me how to generate the csv file successfully whenever the order gets placed.
i keep getting errors like: Object of class Magento\Sales\Model\Order\Address could not be converted to string
Class Order implements ObserverInterface
{
protected $_request;
protected $_order;
protected $_productRepository;
protected $_scopeConfig;
protected $_customer;
protected $_storemanager;
public function __construct(
\Magento\Framework\App\RequestInterface $request,
\Magento\Sales\Model\Order $order,
\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
Filesystem $filesystem,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Customer\Model\Customer $customer,
\Magento\Store\Model\StoreManagerInterface $storemanager,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Sales\Model\OrderFactory $orderFactory,
\Magento\Framework\ObjectManager\ObjectManager $objectManager,
\Psr\Log\LoggerInterface $logger,
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Catalog\Model\ProductRepository $productRepository
) {
$this->_scopeConfig = $scopeConfig;
$this->_customer = $customer;
$this->_storemanager = $storemanager;
$this->_request = $request;
$this->_order = $order;
$this->_fileFactory = $fileFactory;
$this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
$this->_productRepository = $productRepository;
}
public function execute(\Magento\Framework\Event\Observer $observer) {
$order = $observer->getEvent()->getOrder();
$websiteID = $this->_storemanager->getStore()->getWebsiteId();
$headers = array( 'Customer Name', 'Customer Email', ' Phone','Shipping Address' ,'SKU','Quantity','Price','Total','Weight');
$name = strtotime('now');
$file = 'customorderexport/'.$name.'_detailed_orderexport.csv';
$this->directory->create('customorderexport');
$stream = $this->directory->openFile($file, 'w+');
$stream->lock();
$stream->writeCsv($headers);
// $orderdetail['Customer Name'] =
$orderdetail['Customer Email'] = $order->getCustomerEmail();
$orderdetail['Contact Phone'] = $order->getTelephone();
$orderdetail['Shipping Address'] = $order->getShippingAddress();
$items = $order->getAllItems();
foreach ($items as $item) {
$orderdetail['SKU'] = $item->getSKU();
$orderdetail['Quantity'] = $item->getQtyOrdered();
$orderdetail['Price'] = $item->getPrice();
$orderdetail['Total'] = $item->getGrandTotal();
$orderdetail['Weight'] = $item->getWeight();
$stream->writeCsv($orderdetail);
}
$stream->unlock();
$stream->close();
}
}
This is because
$order->getShippingAddress();
will return a OrderAddressInterface object. (Magento\Sales\Api\Data\OrderAddressInterface)
You could do following for example:
$shippingAddress = $order->getShippingAddress();
$orderdetail['Shipping Address'] = $shippingAddress->getStreet()[0];

Zend_Paginator for Categories

I have used Zend_Paginator in my Index action , this show all my catalog :
public function indexAction()
{
Zend_View_Helper_PaginationControl::setDefaultViewPartial('/pagination.phtml');
$pages = new Application_Model_DbTable_Catalog();
$num = 10;
$page = $this->_getParam('page');
$select = $pages->select();
$result = $this->view->table = $pages->fetchAll($select)->toArray();
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($result));
$paginator->setItemCountPerPage($num);
$paginator->setCurrentPageNumber($page);
$paginator->setView($this->view);
$this->view->paginator = $paginator;
}
It works perfectly, now I have CategoryAction, it's sort my catalog by category
public function categoryAction()
{
$id = intval($this->_getParam('id', 0));
if ($id > 0) {
$catalog = new Application_Model_DbTable_Catalog();
$this->view->catalog = $catalog->getByCategoryId($id);
и
$category = new Application_Model_DbTable_Categories();
$this->view->category = $category->getById($id);
}
So I can't understand how to add Pagination to this action,
Help me, Pleaaasssseeeeeee:-(,
P.S. sorry for my bad English
Ok there is a better/easier way to do this.
Pagination starts with your database query. You are using DbTable models so it's very easy in ZF1 to setup the adapter.
<?php
class Application_Model_DbTable_Catalog extends Zend_Db_Table_Abstract
{
protected $_name = 'catalog'
/*
* This method returns a paginator adapter with a fetchAll($where = null, $order = null, $count = null, $offset = null)
* paginator adapter will supply the values for $offset and $limit
*/
public function getPagedCatalog()
{
$select = $this->select(); //put anything you need into $select
$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);//the paginator adapter in place of the fetchAll().
return $adapter;
{
}
<?php
class Application_Model_DbTable_Categories extends Zend_Db_Table_Abstract
{
protected $_name = 'categories'
/*
* This method returns a paginator adapter with a fetchAll($where = $id, $order = null, $count = null, $offset = null)
* paginator adapter will supply the values for $offset and $limit
*/
public function getPagedCatagories($id)
{
$select = $this->select(); //put anything you need into $select
$select->where('catagory_id = ?', $id);//you may need to build a join for this to work how you want it to, depends on your table structure.
$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);//the paginator adapter in place of the fetchAll().
return $adapter;
{
}
now your models will return paginator adapters with the contents of these tables available. Zend_Paginator will automatically supply the $limit and $offset parameters to the query so that each page will perform a query. The whole table will not be stored in memory with this adapter.
Now your indexAction() may look like:
public function indexAction()
{
Zend_View_Helper_PaginationControl::setDefaultViewPartial('/pagination.phtml');
$pages = new Application_Model_DbTable_Catalog();
$adapter = $pages->getPagedCatalog(); //get adapter from model
$page = $this->_getParam('page', 1);//a default of page 1 prevents possible unusual behavior when no page number is set.
$paginator = new Zend_Paginator($adapter);
$paginator->setItemCountPerPage('10');
$paginator->setCurrentPageNumber($page);
//$paginator->setView($this->view); This line is likely not needed
$this->view->paginator = $paginator;
}
and your categoryAction() might work like:
public function categoryAction()
{
$page = $this->_getParam('page', 1);
$id = intval($this->_getParam('id', 0));
if ($id > 0) {
$category = new Application_Model_DbTable_Categories();
$adapter = $category->getPagedCatagories($id);
//same as above
$paginator = new Zend_Paginator($adapter);
$paginator->setItemCountPerPage('10');
$paginator->setCurrentPageNumber($page);
//$paginator->setView($this->view); This line is likely not needed, unless you have multiple view objects.
$this->view->paginator = $paginator;
} else {
//do some other stuff...
}
}
if you get crazy and want to use your own mapper classes to base a paginator adapter on you can extend the adapter class by overriding getItems(), something like:
<?php
class Music_Model_Paginator_Track extends Zend_Paginator_Adapter_DbTableSelect
{
//override getItems()
public function getItems($offset, $itemCountPerPage)
{
$rows = parent::getItems($offset, $itemCountPerPage);
$albums = array();
foreach ($rows as $row) {
$album = new Music_Model_Mapper_Track();//use this class to turn each $row into an object
$albums[] = $album->createEntity($row); //build the new entity objects
}
//returns an array of entity objects to the paginator
return $albums;
}
}
Hope this helps.

How to use locale in select query in Zend model

On my administrator cms I can add newsitems and add a language code in column 'language' to the newsitem 'en' or 'nl'. In the bootstrapfile the language is set through:
public function _initLanguage()
{
$objSessionLanguage= new Zend_Session_Namespace('Zend_Lang');
$objLocale = new Zend_Locale();
$locale = new Zend_Locale();
$language = $locale->getLanguage();
$region = $locale->getRegion();
Zend_Loader::loadClass('Zend_Controller_Request_Http');
$request = new Zend_Controller_Request_Http();
if($language=='nl' or $language=='en')
{
if($language=='nl')
{
$localFile = 'dutch.php';
$Locale = 'nl';
}else
{ {
$localFile = 'english.php';
$Locale = 'en';
}
$objSessionLanguage->localFile=$localFile;
$objSessionLanguage->Locale=$Locale;
}else
{
if(!isset($objSessionLanguage->localFile))
{
$localFile = 'english.php';
$Locale = 'en';
}else
{
$localFile = $objSessionLanguage->localFile;
$Locale =$objSessionLanguage->Locale;
}
}
$objTranslate = new Zend_Translate('array', APPLICATION_PATH .'/../language/english.php', 'en');
$objTranslate->addTranslation(APPLICATION_PATH .'/../language/'.$localFile, $Locale);
$objTranslate->setLocale($Locale);
Zend_Registry::set("Zend_Translate", $objTranslate);
}
To display newsitems in a NewsList I want to select the newsitems in the newsmodel depending on language.
<?php
class Admin_Model_News extends Zend_Db_Table_Abstract
{
protected $_modelName = 'news';
protected $_modelLabel = 'News';
protected $_name = 'news';
protected $_objGeneralSettingVar;
public function init()
{
parent::init();
$this->_objGeneralSettingVar = Zend_Registry::get( "objGeneralSettingVar");
}
public function fetchNewsList()
{
$objSelect = $this->select()->limit(5);
$objSelect->where ("language = '$language'");
$objSelect->order("news_date DESC");
return $this->fetchAll($objSelect)->toArray();
}
}
But with the above
$objSelect->where ("language = '$language'");
no newsitems is displayed. I am sure I am missing something but can not seem to find it. How can I use the language setting in selecting newsitems on language?
In Admin_Model_News you are using
$objSelect->where ("language = '$language'");
for your where clause, but $language has not been set anywhere, so you are querying Where language = null.
The function fetchNewsList should look like this:-
public function fetchNewsList($language)
{
$objSelect = $this->select()->limit(5);
$objSelect->where ("language = '$language'");
$objSelect->order("news_date DESC");
return $this->fetchAll($objSelect)->toArray();
}
You don't show how you are using Admin_Model_News, but it should be something like this:-
$news = new Admin_Model_News();
$newList = $news->fetchNewsList(howeverYouGetlanguage());

zend form not working when calling to multiple page

I have a controller action
public function pagedetailAction(){
$id = $this->_getParam('id',0);
$detail = new Application_Model_Page();
$this->view->detail = $detail->findArr($id);
//CALLING FORM WITH OTHER CONTENTS
$form = new Application_Form_Request();
$this->view->form = $form;
}
To process the form I have this function
public function submitrequestAction(){
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$newsadd = new Application_Model_Request($formData);
$newsadd->set_ID(null);
$newsadd->save();
$this->_helper->flashMessenger->addMessage(array('success'=>'Message Sent'));
$this->_redirect('/index/frontmsg');
} else {
$form->populate($formData);
}
}
}
when i click submit i get the error
Notice: Undefined variable: form in E:\xampp\htdocs\sandbox1\application\controllers\IndexController.php on line 84
Fatal error: Call to a member function isValid() on a non-object in E:\xampp\htdocs\sandbox1\application\controllers\IndexController.php on line 84
Please help me so that I can post values to database via this form. Thanks
Use this
public function submitrequestAction(){
if ($this->getRequest()->isPost()) {
$form = new Application_Form_Request();//added this
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$newsadd = new Application_Model_Request($formData);
$newsadd->set_ID(null);
$newsadd->save();
$this->_helper->flashMessenger->addMessage(array('success'=>'Message Sent'));
$this->_redirect('/index/frontmsg');
} else {
$form->populate($formData);
}
}
}
Add $form initialization to your submitrequestAction:
$form = new Application_Form_Request();

Zend Framework - Passing a variable request in controller

In one of these php frameworks I've noticed a posibility to request the object Request in action as $this->request->paramName
class MyRequest extends Zend_Controller_Request_Http{
public $params = array();
public function __construct() {
$this->params = $this->getParams();
parent::__construct();
}
public function __get($name) {
if (isset($this->_params[$name])) {
return $this->_params[$name];
}
}
public function __isset($name) {
return isset($this->_params[$name]);
}
}
in MyController I've added variable request
public $request = null;
How can I change that standart Request to my one?
public function __construct(
Zend_Controller_Request_Abstract $request,
Zend_Controller_Response_Abstract $response,
array $invokeArgs = array()) {
$request = new MyRequest();
parent::__construct($request, $response, $invokeArgs);
$this->request = $this->getRequest();
}
This function has given no results.
Option 1 is make method _initRequest() in bootstrap:
protected function _initRequest() {
$this->bootstrap ( 'FrontController' );
$front = $this->getResource ( 'FrontController' );
$request = $front->getRequest ();
if (null === $front->getRequest ()) {
$request = new MyRequest();
$front->setRequest ( $request );
}
return $request;
}
A bit dirty and untested solution. Would love to hear if it works.
//Bootstrap:
public function _initRequest()
{
$this->bootstrap('frontController');
$front = $this->getResource('frontController');
$front->setRequest(new MyRequest());
}
Try this it might help you:
in controller file
public function exampleAction(){
$result = $this->_request;
$model = new Employer_Model_JobInfo();
$results = $model->sample($result);
}
// the above line stores the values sent from the client side in $result.then sends that values to Model file with parameter $result ..
in model file
class Employer_Model_JobInfo extends Gears_Db_Table_Abstract{
public function sample($param){
$paramVal = $param->getParam('name');
$paramVal1 = $param->getParam('email');
}
}
The name and email are what name used to sent the data from client to server.