CakePHP login when trying to acces controller - session

im having troubles with a web app that a teacher ask me to modify, the problem its that i dont know about cakePHP and i have been having troubles.After reading a lot, i think i have grasped the basics of the framework. My problem now its that i have a link in a view so i call a function in the controller to retrive data from the model, the problem its that each time i try to acces the function , the app makes me log in, and the idea its that it shouldnt.
I dont know exactly how the session handling on cakePhp works so, im requesting some help.
the code for the controller its this:
<?php
class RwController extends AppController {
var $name = 'Rw';
// var $paginate = array(
// 'Tip' => array(
// 'limit' => 1,
// 'order' => array(
// 'tip.created' => 'desc'
// ),
// ),
// 'Evento' => array(
// 'limit' => 1,
// 'order' => array(
// 'evento.fecha' => 'desc'
// ),
// )
// );
function map() {
$this->helpers[]='GoogleMapV3';
}
function pageForPagination($model) {
$page = 1;
// $chars = preg_split('/model:/', $this->params['url']['url'], -1, PREG_SPLIT_OFFSET_CAPTURE);
// #print_r($chars);
// if(sizeof($chars) > 1 && sizeof($chars) < 3) {
// #echo "Belongs to ".$model.": \n";
// #echo var_dump($chars);
// }
// $params = Dispatcher::parseParams(Dispatcher::uri());
// echo "<p>".var_dump($params)."</p><br />";
#echo $this->params['named']['model'].$model;
#echo $this->params['named']['page'];
$sameModel = isset($this->params['named']['model']) && $this->params['named']['model'] == $model;
$pageInUrl = isset($this->params['named']['page']);
if ($sameModel && $pageInUrl) {
$page = $this->params['named']['page'];
} else {
#echo var_dump($this->passedArgs);
}
$this->passedArgs['page'] = $page;
return $page;
}
function index() {
$this->log('indexeando esta chingadera','debug');
$this->loadModel('User');
$this->loadModel('Evento');
$this->loadModel('Tip');
$dataEvento = $this->Evento->find('all');
$dataTip = $this->Tip->find('all');
$page = $this->pageForPagination('Evento');
$this->paginate['Evento'] = array(
'contain' => false,
'order' => array('Evento.fecha' => 'desc'),
'limit' => 1,
'page' => $page
);
$dataEvento = $this->paginate('Evento');
$page = $this->pageForPagination('Tip');
$this->paginate['Tip'] = array(
'contain' => false,
'order' => array('Tip.created' => 'desc'),
'limit' => 1,
'page' => $page
);
$dataTip = $this->paginate('Tip');
$this->set('users', $this->User->find('all'));
$this->set('eventos', $dataEvento);
$this->set('tips', $dataTip);
$this->set('rw');
if(isset($this->params['named']['model'])) {
if (strcmp($this->params['named']['model'], 'Evento') == 0) {
if($this->RequestHandler->isAjax()) {
$this->render('/elements/ajax_rw_evento_paginate');
return;
}
} elseif (strcmp($this->params['named']['model'], 'Tip') == 0) {
if($this->RequestHandler->isAjax()) {
$this->render('/elements/ajax_rw_tip_paginate');
return;
}
}
}
}
function about($id = null) {
$this->Rw->recursive = 0;
$this->set('rw', $this->paginate());
}
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('index', 'about'));
}
function getCentros($id){
$this->loadModel('Centro');
$this->log('getcentros','debug');
if( sizeof($id) > 1){
$this->set('centros', $this->Centro->query("SELECT centros.id, name, latitud ,longitud
FROM `centros`,`centrosmateriales`
WHERE centros.id = centro_id
AND material_id ='".$id[0]."'
OR material_id='".$id[1]."'"));
}elseif( sizeof($id) >0) {
if($id == 0){
$this->set('centros', $this->Centro->find('all'));
}else{
$this->set('centros', $this->Centro->query("SELECT centros.id, name, latitud ,longitud
FROM `centros`,`centrosmateriales`
WHERE centros.id = centro_id
AND material_id ='".$id[0]."'"));
}
}
$this->redirect(array('action' => 'index'));
}
}
?>
Edit:
The function im calling is getCentros().
this is what i have in app_controller.
<?php
class AppController extends Controller {
var $components = array('Session', 'Auth', 'RequestHandler');
var $helpers = array('Html', 'Form', 'Time', 'Session', 'Js', 'Paginator', 'GoogleMapV3');
function beforeFilter() {
$this->Auth->userModel = 'User';
$this->Auth->fields = array('username' => 'email', 'password' => 'password');
$this->Auth->loginAction = array('admin' => false, 'controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'index');
}
}
?>

try this
$this->Auth->allow(array('*'));
it allows you to access all functions inside the controller.
But before that make sure that you have access on the controller with out errors because your controller name is like this
class RwController extends AppController {
}
may be it want like this
class RwsController extends AppController {
}

Don't know which function you are trying to call but if cake tries to log you in and you don'want this add the function to:
$this->Auth->allow(array('index', 'about'));
in your beforefilter

Related

Payment failed but order is Placed in Laravel with Stripe

I have integrated stripe payment in flutter app but After payment got failed even then order placed in Laravel database so please check, what I have done wrong.
Please check at save method, May be I am wrong and can't validate purchase response.
payment controller
public function makePayment(Request $request)
{
try{
$data = $request->input('cartItems');
$cartItems = json_decode($data, true);
$orderData = $request->input('order');
$selectPaymentOption = json_decode($orderData, true);
$totalAmount = 0.0;
foreach ($cartItems as $cartItem){
$order = new Order();
$order->order_date = Carbon::now()->toDateString();
$order->product_id = $cartItem['productId'];
$order->payment_type = $selectPaymentOption['paymentType'];
$order->user_id = $request->input('userId');
$order->quantity = $cartItem['productQuantity'];
$order->amount = ($cartItem['productPrice'] - $cartItem['productDiscount']);
$totalAmount+= $order->amount * $order->quantity;
$order->save();
}
if($selectPaymentOption['paymentType'] == 'Card'){
\Stripe\Stripe::setApiKey('sk_test_hJUgYYzeXtitxxxx71lK8nE00MELJJS8c');
$token = \Stripe\Token::create([
'card' => [
'number' => $request->input('cardNumber'),
'exp_month' => $request->input('expiryMonth'),
'exp_year' => $request->input('expiryYear'),
'cvc' => $request->input('cvcNumber')
]
]);
$charge = \Stripe\Charge::create([
'amount' => $totalAmount * 100,
'currency' => 'inr',
'source' => $token,
'receipt_email' => $request->input('email'),
]);
}
return response(['result' => true]);
} catch (\Exception $exception){
return response(['result' => $exception]);
}
}
and my Flutter's Post request is here.
I want to POST _makePayment method after complete payment successful.
void _makePayment(BuildContext context, Payment payment) async {
PaymentService _paymentService = PaymentService();
var paymentData = await _paymentService.makePayment(payment);
var result = json.decode(paymentData.body);
print(paymentData);
CartService _cartService = CartService();
this.widget.cartItems!.forEach((cartItem) {
_cartService.makeTheCartEmpty();
});
if (result['result'] == true) {
_showPaymentSuccessMessage(context);
Timer(Duration(seconds: 4), () {
Navigator.pop(context);
Navigator.push(
context, MaterialPageRoute(builder: (context) => HomeScreen()));
});
}
}
Referring to my comment above, this is the rough solution I suggested in your controller you have to switch the logic
public function makePayment(Request $request)
{
try{
$data = $request->input('cartItems');
$cartItems = json_decode($data, true);
$orderData = $request->input('order');
$selectPaymentOption = json_decode($orderData, true);
##Change your frontend logic to pass total amount as variable
$totalAmount = $request->totalAmount;
if($selectPaymentOption['paymentType'] == 'Card'){
##Never have any sk or pk in your controller, switch this to config('common.sk_test')
\Stripe\Stripe::setApiKey(config('common.sk_test'));
$token = \Stripe\Token::create([
'card' => [
'number' => $request->input('cardNumber'),
'exp_month' => $request->input('expiryMonth'),
'exp_year' => $request->input('expiryYear'),
'cvc' => $request->input('cvcNumber')
]
]);
$charge = \Stripe\Charge::create([
'amount' => $totalAmount * 100,
'currency' => 'inr',
'source' => $token,
'receipt_email' => $request->input('email'),
]);
}
##After the stripe transaction is finished you can foreach your cart and do what you need to your database
foreach ($cartItems as $cartItem){
$order = new Order();
$order->order_date = Carbon::now()->toDateString();
$order->product_id = $cartItem['productId'];
$order->payment_type = $selectPaymentOption['paymentType'];
$order->user_id = $request->input('userId');
$order->quantity = $cartItem['productQuantity'];
$order->amount = ($cartItem['productPrice'] - $cartItem['productDiscount']);
$order->save();
}
return response(['result' => true]);
} catch (\Exception $exception){
return response(['result' => $exception]);
}
}
For the config('common.sk_test') part of my answer, in you config folder you can create a new file where you have you custom app variables, so create a file for instance common.php and 'sk_test' that takes its value from you .env file

Extend Laravel package

I've searched around and couldn't find a definitive answer for this...
I have a package DevDojo Chatter and would like to extend it using my application. I understand I'd have to override the functions so that a composer update doesn't overwrite my changes.
How do I go about doing this?
UPDATE
public function store(Request $request)
{
$request->request->add(['body_content' => strip_tags($request->body)]);
$validator = Validator::make($request->all(), [
'title' => 'required|min:5|max:255',
'body_content' => 'required|min:10',
'chatter_category_id' => 'required',
]);
Event::fire(new ChatterBeforeNewDiscussion($request, $validator));
if (function_exists('chatter_before_new_discussion')) {
chatter_before_new_discussion($request, $validator);
}
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
$user_id = Auth::user()->id;
if (config('chatter.security.limit_time_between_posts')) {
if ($this->notEnoughTimeBetweenDiscussion()) {
$minute_copy = (config('chatter.security.time_between_posts') == 1) ? ' minute' : ' minutes';
$chatter_alert = [
'chatter_alert_type' => 'danger',
'chatter_alert' => 'In order to prevent spam, please allow at least '.config('chatter.security.time_between_posts').$minute_copy.' in between submitting content.',
];
return redirect('/'.config('chatter.routes.home'))->with($chatter_alert)->withInput();
}
}
// *** Let's gaurantee that we always have a generic slug *** //
$slug = str_slug($request->title, '-');
$discussion_exists = Models::discussion()->where('slug', '=', $slug)->first();
$incrementer = 1;
$new_slug = $slug;
while (isset($discussion_exists->id)) {
$new_slug = $slug.'-'.$incrementer;
$discussion_exists = Models::discussion()->where('slug', '=', $new_slug)->first();
$incrementer += 1;
}
if ($slug != $new_slug) {
$slug = $new_slug;
}
$new_discussion = [
'title' => $request->title,
'chatter_category_id' => $request->chatter_category_id,
'user_id' => $user_id,
'slug' => $slug,
'color' => $request->color,
];
$category = Models::category()->find($request->chatter_category_id);
if (!isset($category->slug)) {
$category = Models::category()->first();
}
$discussion = Models::discussion()->create($new_discussion);
$new_post = [
'chatter_discussion_id' => $discussion->id,
'user_id' => $user_id,
'body' => $request->body,
];
if (config('chatter.editor') == 'simplemde'):
$new_post['markdown'] = 1;
endif;
// add the user to automatically be notified when new posts are submitted
$discussion->users()->attach($user_id);
$post = Models::post()->create($new_post);
if ($post->id) {
Event::fire(new ChatterAfterNewDiscussion($request));
if (function_exists('chatter_after_new_discussion')) {
chatter_after_new_discussion($request);
}
if($discussion->status === 1) {
$chatter_alert = [
'chatter_alert_type' => 'success',
'chatter_alert' => 'Successfully created a new '.config('chatter.titles.discussion').'.',
];
return redirect('/'.config('chatter.routes.home').'/'.config('chatter.routes.discussion').'/'.$category->slug.'/'.$slug)->with($chatter_alert);
} else {
$chatter_alert = [
'chatter_alert_type' => 'info',
'chatter_alert' => 'You post has been submitted for approval.',
];
return redirect()->back()->with($chatter_alert);
}
} else {
$chatter_alert = [
'chatter_alert_type' => 'danger',
'chatter_alert' => 'Whoops :( There seems to be a problem creating your '.config('chatter.titles.discussion').'.',
];
return redirect('/'.config('chatter.routes.home').'/'.config('chatter.routes.discussion').'/'.$category->slug.'/'.$slug)->with($chatter_alert);
}
}
There's a store function within the vendor package that i'd like to modify/override. I want to be able to modify some of the function or perhaps part of it if needed. Please someone point me in the right direction.
If you mean modify class implementation in your application you can change the way class is resolved:
app()->bind(PackageClass:class, YourCustomClass::class);
and now you can create this custom class like so:
class YourCustomClass extends PackageClass
{
public function packageClassYouWantToChange()
{
// here you can modify behavior
}
}
I would advise you to read more about binding.
Of course a lot depends on how class is created, if it is created using new operator you might need to change multiple classes but if it's injected it should be enough to change this single class.

How to make the field reuired in Yii2 recaptcha google extension himiklab

I am using extension himiklab for yii2 recaptcha, which is similar to the google one. I want to set this field as required field in my rules. When I set it as below it is not validating even If I don't click the checkbox.
[['reCaptcha'], 'required'],
['reCaptcha', \himiklab\yii2\recaptcha\ReCaptchaValidator::className(), 'secret' => '***','skipOnEmpty' => false],
view
<?= $form->field($model, 'reCaptcha')->widget(
\himiklab\yii2\recaptcha\ReCaptcha::className(),
['siteKey' => '6LeY1BAUAAAAALThRhBQ-sJaXbP0Z5i9XFuaz_VW']
)->label(false); ?>
action
public function actionSignup()
{
$browser = new Browser;
if( $browser->getBrowser() == Browser::BROWSER_IE && $browser->getVersion() < 11 )
{
return $this->render('browser');
}
$company = new Company();
$model = new SimUser(['scenario' => SimUser::SCENARIO_REGISTER]);
if ($model->load(Yii::$app->request->post())&& $model->validate() && $company->load(Yii::$app->request->post())&& $company->validate()) {
$model->scenario = SimUser::SCENARIO_REGISTER;
$model->setPassword($model->user_password_hash);
// $model->setCaptcha($model->captcha);
$model->generateAuthKey();
$token = Yii::$app->security->generateRandomString();
$model->user_access_token = $token;
$model->user_verify = 1;
// $company->save();
$model->company_id = 3;
// $model->save();
$model->user_id = 44;
var_dump($model->validate());exit();
if ($model->validate()){
// $auth = Yii::$app->authManager;
// $authorRole = $auth->getRole('Company Admin');
// $auth->assign($authorRole, $model->user_id);
$path = 'C:/wamp/www/test.qsims.com/web/gentelella-1.2.0/production/images/DCMLogo.png';
Yii::$app->mailer->compose('#app/mail/layouts/verify',['model' => $model, 'path' => $path,'token' => $model->user_access_token])
->setTo($model->user_email)
->setFrom('test.qsims#gmail.com')
->setSubject('Welcome to Qsims'.$model->user_fname." ".$model->user_lname.'. Verify your account to continue')
->setTextBody('Verify Account')
->send();
}
// \Yii::$app->user->login($model);
return $this->redirect(['site/verify-new']);
}
return $this->render('signup', [
'model' => $model,
'company' => $company,
]);
}
Where am I going wrong?
Add this to the model
Public $reCaptcha;
add this to rules
['reCaptcha', 'reCaptchaValidator']
call the custom validation
public function reCaptchaValidator($attribute)
{
$validator = new ReCaptchaValidator;
if (!$validator->validate($this->reCaptcha, $error)) {
$this->addError($attribute, $error);
}
}

Creating a grid in admin panel on click of a dropdown option magento 1.7.0.2

I'm developing a sub-module in the admin panel. The first page grid shows the list of the users(Referrers / Parent users) and their total commission. In the "Actions" tab there's a drop-down, on click of which some grids get opened. Similar to it, I want to add another option on click of which there should be a page showing who referred (child users) under that Referrer / Parent user and how much commission the Referrer / Parent user got per referral / child user.
For ex: A (Parent user) - B ,C (child users) got registered by the reference of A.
So, From B, A got 20$ commission and from C, A got 20$ commission, (these details of who referred by whom and how much of commission is there is stored in a table) showing total of 40$ on previous page.
The error which I'm getting is-
Fatal error: Uncaught Error: Call to a member function setSaveParametersInSession() on boolean in E:\xampp\htdocs\peoplesoilnew\app\code\core\Mage\Adminhtml\Block\Widget\Grid\Container.php:66 Stack trace: #0 E:\xampp\htdocs\peoplesoilnew\app\code\core\Mage\Core\Block\Abstract.php(238): Mage_Adminhtml_Block_Widget_Grid_Container->_prepareLayout() #1 E:\xampp\htdocs\peoplesoilnew\app\code\core\Mage\Core\Model\Layout.php(456): Mage_Core_Block_Abstract->setLayout(Object(Mage_Core_Model_Layout)) #2 E:\xampp\htdocs\peoplesoilnew\app\code\local\Mj\Friends\controllers\Adminhtml\FriendsController.php(60): Mage_Core_Model_Layout->createBlock('friends/adminht...') #3 E:\xampp\htdocs\peoplesoilnew\app\code\core\Mage\Core\Controller\Varien\Action.php(419): Mj_Friends_Adminhtml_FriendsController->friendscommissionAction() #4 E:\xampp\htdocs\peoplesoilnew\app\code\core\Mage\Core\Controller\Varien\Router\Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('friendscommissi...') #5 E:\xampp\htdocs\peoplesoilnew\app\code\core\Ma in E:\xampp\htdocs\peoplesoilnew\app\code\core\Mage\Adminhtml\Block\Widget\Grid\Container.php on line 66
Code files-
The code from where the option for drop-down is added -
$this->addColumn('action',
array(
'header' => Mage::helper('customer')->__('Action'),
'width' => '100',
'type' => 'action',
'getter' => 'getId',
'actions' => array(
array(
'caption' => Mage::helper('friends')->__('Make Payment'),
'url' => array('base'=> '*/*/payment'),
'field' => 'friendskey_id'
),
array(
'caption' => Mage::helper('friends')->__('View Referred Friend List'),
'url' => array('base'=> '*/*/friendslist'),
'field' => 'friendskey_id'
),
array(
'caption' => Mage::helper('friends')->__('Distribution of Commission'),
'url' => array('base'=> '*/*/friendscommission'),
'field' => 'friendskey_id'
)
app\code\local\Mj\Friends\etc\config.xml -
<friends_mysql4>
<class>Mj_Friends_Model_Mysql4</class>
<entities>
<friends>
<table>friends</table>
</friends>
<commission>
<table>friends_commission</table>
</commission>
<memberkey>
<table>friendskey</table>
</memberkey>
<friendscommission>
<table>friends_commission</table>
</friendscommission>
</entities>
</friends_mysql4>
app\code\local\Mj\Friends\Block\Adminhtml\Friendscommission\Grid.php -
<?php
class Mj_Friends_Block_Adminhtml_Friendscommission_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('friends_commission');
$this->setDefaultSort('commission_id');
$this->setDefaultDir('ASC');
$this->setSaveParametersInSession(false);
$this->_prepareCollection();
}
protected function _prepareCollection()
{
// get the member id using friendskey_id
/*$friendsId = $this->getRequest()->getParam('friendskey_id');
$friendsModel = Mage::getModel('friends/memberkey')->load($friendsId);
$memberId = $friendsModel->getMemberId();*/
$collection = Mage::getModel('friends/friends_commission')->getCollection();
// $collection->addFieldToFilter('member_id', $memberId);
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
/*
$this->addColumn('friends_id', array(
'header' => Mage::helper('friends')->__('ID'),
'align' =>'right',
'width' => '50px',
'index' => 'friends_id',
));
*/
$this->addColumn('user_email', array(
'header' => Mage::helper('friends')->__('User Email'),
'align' => 'left',
'width' => '120px',
'default' => '--',
'index' => 'user_email',
));
$this->addColumn('status', array(
'header' => Mage::helper('friends')->__('Status'),
'align' => 'left',
'width' => '80px',
'index' => 'status',
'type' => 'options',
'options' => array(
'Active' => 'Active',
'Inactive' => 'Inactive',
),
));
return parent::_prepareColumns();
}
}
app\code\local\Mj\Friends\Block\Adminhtml\Friendscommission.php -
<?php
class Mj_Friends_Block_Adminhtml_Friendscommission extends Mage_Adminhtml_Block_Widget_Grid_Container
{
public function __construct()
{
$this->_controller = 'adminhtml_friendscommission';
$this->_blockGroup = 'friends';
$this->_headerText = Mage::helper('friends')->__('Friends Commission');
//$this->_addButtonLabel = Mage::helper('friends')->__('Add Item');
parent::__construct();
$this->_removeButton('add');
/*
$this->_addButton('back');
$this->_addButton('back_button_id', array(
'label' => Mage::helper('friends')->__('Some action'),
'onclick' => 'jsfunction(this.id)',
'class' => 'go'
), 0, 100, 'header', 'header');
*/
}
}
**app\code\local\Mj\Friends\Model\Friendscommission.php **
<?php
class Mj_Friends_Model_Friendscommission extends Mage_Core_Model_Abstract
{
public function _construct()
{
parent::_construct();
$this->_init('friends/friends_commission');
}
}
From the controller the action for that module is called, app\code\local\Mj\Friends\controllers\Adminhtml\FriendsController.php -
<?php
class Mj_Friends_Adminhtml_FriendsController extends Mage_Adminhtml_Controller_Action
{
protected function _initAction()
{
$this->loadLayout()
->_setActiveMenu('friends/items')
->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));
return $this;
}
public function indexAction() {
$this->_initAction();
$this->_addContent($this->getLayout()->createBlock('friends/adminhtml_friends'));
$this->renderLayout();
}
public function editAction()
{
$friendsId = $this->getRequest()->getParam('id');
$friendsModel = Mage::getModel('friends/friends')->load($friendsId);
if ($friendsModel->getId() || $friendsId == 0) {
Mage::register('friends_data', $friendsModel);
$this->loadLayout();
$this->_setActiveMenu('friends/items');
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('friends/adminhtml_friends_edit'))
->_addLeft($this->getLayout()->createBlock('friends/adminhtml_friends_edit_tabs'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('friends')->__('Item does not exist'));
$this->_redirect('*/*/');
}
}
public function newAction()
{
$this->_forward('edit');
}
public function friendslistAction() {
$this->_initAction();
$this->_addContent($this->getLayout()->createBlock('friends/adminhtml_friendslist'));
$this->renderLayout();
}
public function friendscommissionAction() {
$this->_initAction();
$this->_addContent($this->getLayout()->createBlock('friends/adminhtml_friendscommission'));
$this->renderLayout();
}
public function paymentAction()
{
$friendsId = $this->getRequest()->getParam('friendskey_id');
$friendsModel = Mage::getModel('friends/memberkey')->load($friendsId);
if ($friendsModel->getFriendskeyId() || $friendsId > 0) {
Mage::register('friends_data', $friendsModel);
$this->loadLayout();
$this->_setActiveMenu('friends/items');
/* $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));*/
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('friends/adminhtml_friends_payment'))
->_addLeft($this->getLayout()->createBlock('friends/adminhtml_friends_payment_tabs'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('friends')->__('Item does not exist'));
$this->_redirect('*/*/');
}
}
public function saveAction()
{
if ( $this->getRequest()->getPost() ) {
try {
$postData = $this->getRequest()->getPost();
//print_r($postData); die;
if($postData['amount_hidden'] ) {
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_write');
$updateSql = "UPDATE friends_standard_payamount SET standard_amount = '".$postData['standard_payment_amount']."', standard_commission = '".$postData['standard_commission']."'";
$readConnection->query($updateSql);
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Minimum referred payment amount updated successfully.'));
$this->_redirect('new', array('friendskey_id' => $this->getRequest()->getParam('friendskey_id')));
return;
} else {
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_write');
$updateSql = "UPDATE friends_standard_payamount SET standard_commission = '".$postData['commission_amount']."'";
$readConnection->query($updateSql);
//get the commission amount
$friendsModel = Mage::getModel('friends/friends');
$commission_amount = $postData['commission_amount'];
$friendskey_id = $postData['friendskey_id'];
//get the memeber id.
$friendsModel = Mage::getModel('friends/memberkey')->load($friendskey_id);
$memberId = $friendsModel->getMemberId();
//get the member paypal business email address.
$customerData = Mage::getModel('customer/customer')->load($memberId)->getData();
//$customerData['paypalemail'];
if(!empty($customerData['paypalemail'])) {
//get the paypal config settings.
$standard = Mage::getModel('paypal/standard');
$form = new Varien_Data_Form();
$form->setAction($standard->getConfig()->getPaypalUrl())
->setId('paypal_standard_checkout')
->setName('paypal_standard_checkout')
->setMethod('POST')
->setUseContainer(true);
/* #var $api Mage_Paypal_Model_Api_Standard */
$api = Mage::getModel('paypal/api_standard')->setConfigObject($this->getConfig());
//$orderIncrementId = 0 ;
$api->setOrderId($orderIncrementId)
->setCurrencyCode(Mage::app()->getStore()->getCurrentCurrencyCode())
//->setPaymentAction()
//->setOrder($order)
->setNotifyUrl(Mage::getUrl('paypal/ipn/'))
->setReturnUrl(Mage::getUrl('paypal/standard/success'))
->setCancelUrl(Mage::getUrl('paypal/standard/cancel'));
//get and set owner address.
$address = array();
$api->setAddress($address);
$api->setLocale($api->getLocaleCode());
$result = $api->getStandardCheckoutRequest();
foreach ($result as $field=>$value) {
if($field == "business") {
//set the paypal business email address
$form->addField($field, 'hidden', array('name'=>$field, 'value'=>$customerData['paypalemail']));
} else if($field == "return") {
$form->addField($field, 'hidden', array('name'=>$field, 'value'=>$this->getUrl('*/*/success', array())));
} else if($field == "cancel_return") {
$form->addField($field, 'hidden', array('name'=>$field, 'value'=>$this->getUrl('*/*/cancel', array())));
} else {
$form->addField($field, 'hidden', array('name'=>$field, 'value'=>$value));
}
}
$form->addField('amount', 'hidden', array('name'=>'amount', 'value'=>$commission_amount));
$form->addField('paymentaction', 'hidden', array('name'=>'paymentaction', 'value'=>'sale'));
$form->addField('item_name', 'hidden', array('name'=>'item_name', 'value'=>'Commission Amount'));
//$form->addField('business', 'hidden', array('name'=>'business', 'value'=>$paypalBusinessIdValue));
$idSuffix = Mage::helper('core')->uniqHash();
$submitButton = new Varien_Data_Form_Element_Submit(array(
'value' => $this->__('Click here if you are not redirected within 10 seconds...'),
));
$id = "submit_to_paypal_button_{$idSuffix}";
$submitButton->setId($id);
$form->addElement($submitButton);
$html = '<html><body>';
$html.= $this->__('You will be redirected to the PayPal website in a few seconds.');
$html.= $form->toHtml();
$html.= '<script type="text/javascript">document.getElementById("paypal_standard_checkout").submit();</script>';
$html.= '</body></html>';
echo $html;
exit;
}else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Member does not have the PayPal Email Address. Thus, unable proceed to make the payment.'));
Mage::getSingleton('adminhtml/session')->setFriendsData($this->getRequest()->getPost());
$this->_redirect('*/*/payment', array('friendskey_id' => $this->getRequest()->getParam('friendskey_id')));
return;
}
}
/*
$friendsModel->setId($this->getRequest()->getParam('id'))
->setTitle($postData['user_email'])
->setContent($postData['content'])
->setStatus($postData['status'])
->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFriendsData(false);
*/
// $this->_redirect('*/*/');
// return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFriendsData($this->getRequest()->getPost());
$this->_redirect('*/*/payment', array('friendskey_id' => $this->getRequest()->getParam('friendskey_id')));
return;
}
}
$this->_redirect('*/*/');
}
public function successAction() {
$this->loadLayout();
$this->_setActiveMenu('friends/items');
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->renderLayout();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Payment has been done successfully.'));
}
public function cancelAction() {
$this->loadLayout();
$this->_setActiveMenu('friends/items');
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->renderLayout();
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Payment has been cancelled successfully.'));
}
public function formAction(){
$this->loadLayout();
$this->getResponse()->setBody(
$this->getLayout()->createBlock('friends/adminhtml_friends_payment_tab_amount')->toHtml()
);
}
/**
* Config instance getter
* #return Mage_Paypal_Model_Config
*/
public function getConfig()
{
if (null === $this->_config) {
$params = array($this->_code);
if ($store = Mage::app()->getStore()) {
$params[] = is_object($store) ? $store->getId() : $store;
}
$this->_config = Mage::getModel('paypal/config', $params);
}
return $this->_config;
}
public function deleteAction()
{
if( $this->getRequest()->getParam('id') > 0 ) {
try {
$friendsModel = Mage::getModel('friends/friends');
$friendsModel->setId($this->getRequest()->getParam('id'))
->delete();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('*/*/');
}
/**
* Product grid for AJAX request.
* Sort and filter result for example.
*/
public function gridAction()
{
$this->loadLayout();
$this->getResponse()->setBody(
$this->getLayout()->createBlock('friends/adminhtml_friends_grid')->toHtml()
);
}
}
The table to fetch data from -
Seems like you are missing the controller "adminhtml_friendscommission"
$this->_controller = 'adminhtml_friendscommission';
Please create the above controller and it will fix the issue.
Or if you dont want that friendscommission controller and if you need to use friends controller change the
$this->_controller = 'adminhtml_friendscommission';
to
$this->_controller = 'adminhtml_friends';
in
Mj_Friends_Block_Adminhtml_Friendscommission::__construct method

CodeIgniter: Passing fields to user_profiles database with Tank_auth

I'm wracking my brain on what is probably a simple issue. Relatively new to MVC and codeigniter. I'm using tank_auth for user registration, and it comes with a db table user_profiles which I've altered slightly to add things like 'firstname', 'lastname', 'homephone', etc.
I've added the appropriate fields to my register_form.php view and following advice from this question: Tank Auth Adding Fields and others, tried to update all necessary stuff. Unfortunately, while the users table gets populated properly, the user_profiles table does not. I've double checked with firebug that the view is posting properly, but the model is not picking up the data, and I keep getting the error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: firstname
Filename: tank_auth/users.php
Line Number: 382
Using var_dump, I can see that the controller function is not receiving 'firstname' or anything else and they are NULL, but the data going into users is being sent properly.
Here's the relevant code:
Model:
private function create_profile($user_id)
{
$this->db->set('user_id', $user_id);
$this->db->set('firstname', $firstname);
return $this->db->insert($this->profile_table_name);
}
Controller:
function register()
{
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/auth/send_again/');
} elseif (!$this->config->item('allow_registration', 'tank_auth')) { // registration is off
$this->_show_message($this->lang->line('auth_message_registration_disabled'));
} else {
$use_username = $this->config->item('use_username', 'tank_auth');
if ($use_username) {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this->config->item('username_min_length', 'tank_auth').']|max_length['.$this->config->item('username_max_length', 'tank_auth').']|alpha_dash');
}
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
$this->form_validation->set_rules('firstname', 'Firstname', 'trim|xss_clean');
$this->form_validation->set_rules('lastname', 'Lastname', 'trim|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']|alpha_dash');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');
$captcha_registration = $this->config->item('captcha_registration', 'tank_auth');
$use_recaptcha = $this->config->item('use_recaptcha', 'tank_auth');
if ($captcha_registration) {
if ($use_recaptcha) {
$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
} else {
$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
}
}
$data['errors'] = array();
$email_activation = $this->config->item('email_activation', 'tank_auth');
if ($this->form_validation->run()) { // validation ok
if (!is_null($data = $this->tank_auth->create_user(
$use_username ? $this->form_validation->set_value('username') : '',
$this->form_validation->set_value('email'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('firstname'),
$this->form_validation->set_value('lastname'),
$this->form_validation->set_value('homephone'),
$this->form_validation->set_value('cellphone'),
$email_activation))) { // success
$data['site_name'] = $this->config->item('website_name', 'tank_auth');
if ($email_activation) { // send "activate" email
$data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;
$this->_send_email('activate', $data['email'], $data);
unset($data['password']); // Clear password (just for any case)
$this->_show_message($this->lang->line('auth_message_registration_completed_1'));
} else {
if ($this->config->item('email_account_details', 'tank_auth')) { // send "welcome" email
$this->_send_email('welcome', $data['email'], $data);
}
unset($data['password']); // Clear password (just for any case)
$this->_show_message($this->lang->line('auth_message_registration_completed_2').' '.anchor('/auth/login/', 'Login'));
}
} else {
$errors = $this->tank_auth->get_error_message();
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
if ($captcha_registration) {
if ($use_recaptcha) {
$data['recaptcha_html'] = $this->_create_recaptcha();
} else {
$data['captcha_html'] = $this->_create_captcha();
}
}
$data['use_username'] = $use_username;
$data['captcha_registration'] = $captcha_registration;
$data['use_recaptcha'] = $use_recaptcha;
$this->load->view('auth/register_form', $data);
}
}
View:
$firstname = array(
'name' => 'firstname',
'id' => 'firstname',
'value' => set_value('firstname'),
'maxlength' => 40,
'size' => 30,
);
...
<tr>
<td><?php echo form_label('First Name', $firstname['id']); ?></td>
<td><?php echo form_input($firstname); ?></td>
<td style="color: red;"><?php echo form_error($firstname['name']); ?><?php echo isset($errors[$firstname['name']])?$errors[$firstname['name']]:''; ?></td>
</tr>
I have been working on this far too long, am hoping that a fresh (and knowledgeable) pair of eyes can see what I cannot.
The data to be recorded in user_profile is passed along the folllowing chain:
view -> controller -> library/tank_auth/create_user() -> model/users/users/create_user() -> model/create_profile
Therefore you need to make sure that the variable is passed along every time.
Here is my working solution, building up on the modifications that you mentioned in the question:
VIEW + CONTROLER:
Your solution is good
LIBRARY
function create_user($username, $email, $password, $firstname, $lastname, $company='', $email_activation)
{
if ((strlen($username) > 0) AND !$this->ci->users->is_username_available($username)) {
$this->error = array('username' => 'auth_username_in_use');
} elseif (!$this->ci->users->is_email_available($email)) {
$this->error = array('email' => 'auth_email_in_use');
} else {
// Hash password using phpass
$hasher = new PasswordHash(
$this->ci->config->item('phpass_hash_strength', 'tank_auth'),
$this->ci->config->item('phpass_hash_portable', 'tank_auth'));
$hashed_password = $hasher->HashPassword($password);
$data = array(
'username' => $username,
'password' => $hashed_password,
'email' => $email,
'last_ip' => $this->ci->input->ip_address(),
);
$data_profile = array(
'firstname' => $firstname,
'lastname' => $lastname,
'company' => $company,
);
if ($email_activation) {
$data['new_email_key'] = md5(rand().microtime());
}
if (!is_null($res = $this->ci->users->create_user($data, $data_profile, !$email_activation))) {
$data['user_id'] = $res['user_id'];
$data['password'] = $password;
unset($data['last_ip']);
return $data;
}
}
return NULL;
}
MODEL:
function create_user($data, $data_profile, $activated = TRUE)
{
$data['created'] = date('Y-m-d H:i:s');
$data['activated'] = $activated ? 1 : 0;
var_dump($data);
if ($this->AuthDb->insert($this->table_name, $data)) {
$user_id = $this->AuthDb->insert_id();
$this->create_profile($user_id, $data_profile);
return array('user_id' => $user_id);
}
return NULL;
}
[...]
private function create_profile($user_id, $data_profile)
{
$this->AuthDb->set('user_id', $user_id);
$this->AuthDb->set('firstname', $data_profile['firstname']);
$this->AuthDb->set('lastname', $data_profile['lastname']);
$this->AuthDb->set('company', $data_profile['company']);
return $this->AuthDb->insert($this->profile_table_name);
}
You need to pass $firstname as a parameter to the function...
private function create_profile($user_id, $firstname)
{
$this->db->set('user_id', $user_id);
$this->db->set('firstname', $firstname);
return $this->db->insert($this->profile_table_name);
}
Ok so I figured it out, in case anyone googles this answer down the line. I'm not sure if this is the 'proper' or most elegant solution, but does fine for my purposes. I edited the create_profile function like so:
private function create_profile($user_id)
{
$this->db->set('user_id', $user_id);
$data = array(
'firstname' => $this->input->post('firstname'),
);
$this->db->insert($this->profile_table_name, $data);
}

Resources