Paypal Plugin sending payment to wrong receiver - plugins

This is not my code***
I am using an open source plugin on a site I am trying to develop. It is a crowdfunding platform and this plugin is suppose to allow payments to be sent directly to project creators. But when I run payment tests in sandbox all payments are being sent to site owner.
I already tried changing the lines in the //prepare payment receiver & //get payment receiver areas from site_owner to project_owner but that did nothing.
I have tried the plugin developer already but haven't heard back so thought I'd see if anyone here could shed some light on the problem for me.
Thanks for any help you can give.
use Crowdfunding\Transaction\Transaction;
use Crowdfunding\Transaction\TransactionManager;
use Crowdfunding\Reward;
use Joomla\Utilities\ArrayHelper;
// no direct access
defined('_JEXEC') or die;
jimport('Prism.init');
jimport('Crowdfunding.init');
jimport('Crowdfundingfinance.init');
jimport('Emailtemplates.init');
JObserverMapper::addObserverClassToClass(
'Crowdfunding\\Observer\\Transaction\\TransactionObserver',
'Crowdfunding\\Transaction\\TransactionManager',
array('typeAlias' => 'com_crowdfunding.payment')
);
/**
* Crowdfunding PayPal payment plugin.
*
* #package Crowdfunding
* #subpackage Plugins
*/
class plgCrowdfundingPaymentPayPal extends Crowdfunding\Payment\Plugin
{
public function __construct(&$subject, $config = array())
{
$this->serviceProvider = 'PayPal';
$this->serviceAlias = 'paypal';
$this->extraDataKeys = array(
'first_name', 'last_name', 'payer_id', 'payer_status',
'mc_gross', 'mc_fee', 'mc_currency', 'payment_status', 'payment_type', 'payment_date',
'txn_type', 'test_ipn', 'ipn_track_id', 'custom', 'protection_eligibility'
);
parent::__construct($subject, $config);
}
/**
* This method prepares a payment gateway - buttons, forms,...
* That gateway will be displayed on the summary page as a payment option.
*
* #param string $context This string gives information about that where it has been executed the trigger.
* #param stdClass $item A project data.
* #param Joomla\Registry\Registry $params The parameters of the component
*
* #throws \InvalidArgumentException
* #throws \UnexpectedValueException
*
* #return string
*/
public function onProjectPayment($context, $item, $params)
{
if (strcmp('com_crowdfunding.payment', $context) !== 0) {
return null;
}
if ($this->app->isAdmin()) {
return null;
}
$doc = JFactory::getDocument();
/** #var $doc JDocumentHtml */
// Check document type
$docType = $doc->getType();
if (strcmp('html', $docType) !== 0) {
return null;
}
// This is a URI path to the plugin folder
$pluginURI = 'plugins/crowdfundingpayment/paypal';
$notifyUrl = $this->getCallbackUrl();
$returnUrl = $this->getReturnUrl($item->slug, $item->catslug);
$cancelUrl = $this->getCancelUrl($item->slug, $item->catslug);
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_NOTIFY_URL'), $this->debugType, $notifyUrl) : null;
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_RETURN_URL'), $this->debugType, $returnUrl) : null;
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_CANCEL_URL'), $this->debugType, $cancelUrl) : null;
$html = array();
$html[] = '<div class="well">';
$html[] = '<h4><img src="' . $pluginURI . '/images/paypal_icon.png" width="36" height="32" alt="PayPal" />' . JText::_($this->textPrefix . '_TITLE') . '</h4>';
// Prepare payment receiver.
$paymentReceiverOption = $this->params->get('paypal_payment_receiver', 'site_owner');
$paymentReceiverInput = $this->preparePaymentReceiver($paymentReceiverOption, $item->id);
if ($paymentReceiverInput === null) {
$html[] = $this->generateSystemMessage(JText::_($this->textPrefix . '_ERROR_PAYMENT_RECEIVER_MISSING'));
return implode("\n", $html);
}
// Display additional information.
$html[] = '<p>' . JText::_($this->textPrefix . '_INFO') . '</p>';
// Start the form.
if ($this->params->get('paypal_sandbox', 1)) {
$html[] = '<form action="' . trim($this->params->get('paypal_sandbox_url')) . '" method="post">';
} else {
$html[] = '<form action="' . trim($this->params->get('paypal_url')) . '" method="post">';
}
$html[] = $paymentReceiverInput;
$html[] = '<input type="hidden" name="cmd" value="_xclick" />';
$html[] = '<input type="hidden" name="charset" value="utf-8" />';
$html[] = '<input type="hidden" name="currency_code" value="' . $item->currencyCode . '" />';
$html[] = '<input type="hidden" name="amount" value="' . $item->amount . '" />';
$html[] = '<input type="hidden" name="quantity" value="1" />';
$html[] = '<input type="hidden" name="no_shipping" value="1" />';
$html[] = '<input type="hidden" name="no_note" value="1" />';
$html[] = '<input type="hidden" name="tax" value="0" />';
// Title
$title = JText::sprintf($this->textPrefix . '_INVESTING_IN_S', htmlentities($item->title, ENT_QUOTES, 'UTF-8'));
$html[] = '<input type="hidden" name="item_name" value="' . $title . '" />';
// Get payment session
$paymentSessionContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $item->id;
$paymentSessionLocal = $this->app->getUserState($paymentSessionContext);
$paymentSessionRemote = $this->getPaymentSession(array(
'session_id' => $paymentSessionLocal->session_id
));
// Prepare custom data
$custom = array(
'payment_session_id' => $paymentSessionRemote->getId(),
'gateway' => $this->serviceAlias
);
$custom = base64_encode(json_encode($custom));
$html[] = '<input type="hidden" name="custom" value="' . $custom . '" />';
// Set a link to logo
$imageUrl = trim($this->params->get('paypal_image_url'));
if ($imageUrl) {
$html[] = '<input type="hidden" name="image_url" value="' . $imageUrl . '" />';
}
// Set URLs
$html[] = '<input type="hidden" name="cancel_return" value="' . $cancelUrl . '" />';
$html[] = '<input type="hidden" name="return" value="' . $returnUrl . '" />';
$html[] = '<input type="hidden" name="notify_url" value="' . $notifyUrl . '" />';
$this->prepareLocale($html);
// End the form.
$html[] = '<img alt="" border="0" width="1" height="1" src="https://www.paypal.com/en_US/i/scr/pixel.gif" >';
$html[] = '</form>';
// Display a sticky note if the extension works in sandbox mode.
if ($this->params->get('paypal_sandbox', 1)) {
$html[] = '<div class="bg-info p-10-5"><span class="fa fa-info-circle"></span> ' . JText::_($this->textPrefix . '_WORKS_SANDBOX') . '</div>';
}
$html[] = '</div>';
return implode("\n", $html);
}
/**
* This method processes transaction data that comes from PayPal instant notifier.
*
* #param string $context This string gives information about that where it has been executed the trigger.
* #param Joomla\Registry\Registry $params The parameters of the component
*
* #throws \InvalidArgumentException
* #throws \OutOfBoundsException
* #throws \RuntimeException
* #throws \UnexpectedValueException
*
* #return null|stdClass
*/
public function onPaymentNotify($context, $params)
{
if (strcmp('com_crowdfunding.notify.'.$this->serviceAlias, $context) !== 0) {
return null;
}
if ($this->app->isAdmin()) {
return null;
}
$doc = JFactory::getDocument();
/** #var $doc JDocumentHtml */
// Check document type
$docType = $doc->getType();
if (strcmp('raw', $docType) !== 0) {
return null;
}
// Validate request method
$requestMethod = $this->app->input->getMethod();
if (strcmp('POST', $requestMethod) !== 0) {
$this->log->add(
JText::_($this->textPrefix . '_ERROR_INVALID_REQUEST_METHOD'),
$this->debugType,
JText::sprintf($this->textPrefix . '_ERROR_INVALID_TRANSACTION_REQUEST_METHOD', $requestMethod)
);
return null;
}
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_RESPONSE'), $this->debugType, $_POST) : null;
// Decode custom data
$custom = ArrayHelper::getValue($_POST, 'custom');
$custom = json_decode(base64_decode($custom), true);
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_CUSTOM'), $this->debugType, $custom) : null;
// Verify gateway. Is it PayPal?
$gateway = ArrayHelper::getValue($custom, 'gateway');
if (!$this->isValidPaymentGateway($gateway)) {
$this->log->add(
JText::_($this->textPrefix . '_ERROR_INVALID_PAYMENT_GATEWAY'),
$this->debugType,
array('custom' => $custom, '_POST' => $_POST)
);
return null;
}
// Get PayPal URL
if ($this->params->get('paypal_sandbox', 1)) {
$url = trim($this->params->get('paypal_sandbox_url', 'https://www.sandbox.paypal.com/cgi-bin/webscr'));
} else {
$url = trim($this->params->get('paypal_url', 'https://www.paypal.com/cgi-bin/webscr'));
}
$paypalIpn = new Prism\Payment\PayPal\Ipn($url, $_POST);
$loadCertificate = (bool)$this->params->get('paypal_load_certificate', 0);
$paypalIpn->verify($loadCertificate);
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_VERIFY_OBJECT'), $this->debugType, $paypalIpn) : null;
// Prepare the array that have to be returned by this method.
$paymentResult = new stdClass;
$paymentResult->project = null;
$paymentResult->reward = null;
$paymentResult->transaction = null;
$paymentResult->paymentSession = null;
$paymentResult->serviceProvider = $this->serviceProvider;
$paymentResult->serviceAlias = $this->serviceAlias;
if ($paypalIpn->isVerified()) {
$containerHelper = new Crowdfunding\Container\Helper();
$currency = $containerHelper->fetchCurrency($this->container, $params);
// Get payment session data
$paymentSessionId = ArrayHelper::getValue($custom, 'payment_session_id', 0, 'int');
$paymentSessionRemote = $this->getPaymentSession(array('id' => $paymentSessionId));
// Check for valid payment session.
if (!$paymentSessionRemote->getId()) {
$this->log->add(JText::_($this->textPrefix . '_ERROR_PAYMENT_SESSION'), $this->errorType, $paymentSessionRemote->getProperties());
return null;
}
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_PAYMENT_SESSION'), $this->debugType, $paymentSessionRemote->getProperties()) : null;
// Validate transaction data
$validData = $this->validateData($_POST, $currency->getCode(), $paymentSessionRemote);
if ($validData === null) {
return null;
}
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_VALID_DATA'), $this->debugType, $validData) : null;
// Set the receiver ID.
$project = $containerHelper->fetchProject($this->container, $validData['project_id']);
$validData['receiver_id'] = $project->getUserId();
// Get reward object.
$reward = null;
if ($validData['reward_id']) {
$reward = $containerHelper->fetchReward($this->container, $validData['reward_id'], $project->getId());
}
// Save transaction data.
// If it is not completed, return empty results.
// If it is complete, continue with process transaction data
$transaction = $this->storeTransaction($validData);
if ($transaction === null) {
return null;
}
// Generate object of data, based on the transaction properties.
$paymentResult->transaction = $transaction;
// Generate object of data based on the project properties.
$paymentResult->project = $project;
// Generate object of data based on the reward properties.
if ($reward !== null and ($reward instanceof Crowdfunding\Reward)) {
$paymentResult->reward = $reward;
}
// Generate data object, based on the payment session properties.
$paymentResult->paymentSession = $paymentSessionRemote;
// Removing intention.
$this->removeIntention($paymentSessionRemote, $transaction);
} else {
// Log error
$this->log->add(
JText::_($this->textPrefix . '_ERROR_INVALID_TRANSACTION_DATA'),
$this->debugType,
array('ERROR MESSAGE' => $paypalIpn->getError(), 'paypalVerify' => $paypalIpn, '_POST' => $_POST)
);
}
return $paymentResult;
}
/**
* Validate PayPal transaction.
*
* #param array $data
* #param string $currencyCode
* #param Crowdfunding\Payment\Session $paymentSessionRemote
*
* #throws \RuntimeException
* #throws \InvalidArgumentException
* #return array
*/
protected function validateData($data, $currencyCode, $paymentSessionRemote)
{
$txnDate = ArrayHelper::getValue($data, 'payment_date');
$date = new JDate($txnDate);
// Prepare transaction data
$transactionData = array(
'investor_id' => $paymentSessionRemote->getUserId(),
'project_id' => $paymentSessionRemote->getProjectId(),
'reward_id' => $paymentSessionRemote->isAnonymous() ? 0 : $paymentSessionRemote->getRewardId(),
'service_provider' => $this->serviceProvider,
'service_alias' => $this->serviceAlias,
'txn_id' => ArrayHelper::getValue($data, 'txn_id', null, 'string'),
'txn_amount' => ArrayHelper::getValue($data, 'mc_gross', null, 'float'),
'txn_currency' => ArrayHelper::getValue($data, 'mc_currency', null, 'string'),
'txn_status' => strtolower(ArrayHelper::getValue($data, 'payment_status', '', 'string')),
'txn_date' => $date->toSql(),
'extra_data' => $this->prepareExtraData($data)
);
// Check Project ID and Transaction ID
if (!$transactionData['project_id'] or !$transactionData['txn_id']) {
$this->log->add(JText::_($this->textPrefix . '_ERROR_INVALID_TRANSACTION_DATA'), $this->errorType, $transactionData);
return null;
}
// Check if project record exists in database.
$projectRecord = new Crowdfunding\Validator\Project\Record(JFactory::getDbo(), $transactionData['project_id']);
if (!$projectRecord->isValid()) {
$this->log->add(JText::_($this->textPrefix . '_ERROR_INVALID_PROJECT'), $this->errorType, $transactionData);
return null;
}
// Check if reward record exists in database.
if ($transactionData['reward_id'] > 0) {
$rewardRecord = new Crowdfunding\Validator\Reward\Record(JFactory::getDbo(), $transactionData['reward_id'], array('state' => Prism\Constants::PUBLISHED));
if (!$rewardRecord->isValid()) {
$this->log->add(JText::_($this->textPrefix . '_ERROR_INVALID_REWARD'), $this->errorType, $transactionData);
return null;
}
}
// Check currency
if (strcmp($transactionData['txn_currency'], $currencyCode) !== 0) {
$this->log->add(JText::_($this->textPrefix . '_ERROR_INVALID_TRANSACTION_CURRENCY'), $this->errorType, array('TRANSACTION DATA' => $transactionData, 'CURRENCY' => $currencyCode));
return null;
}
// Check payment receiver.
$allowedReceivers = array(
strtolower(ArrayHelper::getValue($data, 'business')),
strtolower(ArrayHelper::getValue($data, 'receiver_email')),
strtolower(ArrayHelper::getValue($data, 'receiver_id'))
);
// Get payment receiver.
$paymentReceiverOption = $this->params->get('paypal_payment_receiver', 'site_owner');
$paymentReceiver = $this->getPaymentReceiver($paymentReceiverOption, $transactionData['project_id']);
if (!in_array($paymentReceiver, $allowedReceivers, true)) {
$this->log->add(JText::_($this->textPrefix . '_ERROR_INVALID_RECEIVER'), $this->errorType, array('TRANSACTION DATA' => $transactionData, 'RECEIVER' => $paymentReceiver, 'ALLOWED RECEIVERS' => $allowedReceivers));
return null;
}
return $transactionData;
}
/**
* Save transaction data.
*
* #param array $transactionData
*
* #throws \RuntimeException
* #throws \InvalidArgumentException
* #throws \UnexpectedValueException
*
* #return Transaction|null
*/
protected function storeTransaction($transactionData)
{
// Get transaction object by transaction ID
$keys = array(
'txn_id' => ArrayHelper::getValue($transactionData, 'txn_id')
);
$transaction = new Transaction(JFactory::getDbo());
$transaction->load($keys);
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_TRANSACTION_OBJECT'), $this->debugType, $transaction->getProperties()) : null;
// Check for existed transaction
// If the current status if completed, stop the payment process.
if ($transaction->getId() and $transaction->isCompleted()) {
return null;
}
// Add extra data.
if (array_key_exists('extra_data', $transactionData)) {
if (!empty($transactionData['extra_data'])) {
$transaction->addExtraData($transactionData['extra_data']);
}
unset($transactionData['extra_data']);
}
// IMPORTANT: It must be before ->bind();
$options = array(
'old_status' => $transaction->getStatus(),
'new_status' => $transactionData['txn_status']
);
// Create the new transaction record if there is not record.
// If there is new record, store new data with new status.
// Example: It has been 'pending' and now is 'completed'.
// Example2: It has been 'pending' and now is 'failed'.
$transaction->bind($transactionData);
// Start database transaction.
$db = JFactory::getDbo();
$db->transactionStart();
try {
$transactionManager = new TransactionManager($db);
$transactionManager->setTransaction($transaction);
$transactionManager->process('com_crowdfunding.payment', $options);
} catch (Exception $e) {
$db->transactionRollback();
$this->log->add(JText::_($this->textPrefix . '_ERROR_TRANSACTION_PROCESS'), $this->errorType, $e->getMessage());
return null;
}
// Commit database transaction.
$db->transactionCommit();
return $transaction;
}
protected function prepareLocale(&$html)
{
// Get country
$countryId = $this->params->get('paypal_country');
$country = new Crowdfunding\Country(JFactory::getDbo());
$country->load($countryId);
$code = $country->getCode();
$code4 = $country->getLocale();
$button = $this->params->get('paypal_button_type', 'btn_buynow_LG');
$buttonUrl = $this->params->get('paypal_button_url');
// Generate a button
if (!$this->params->get('paypal_button_default', 0)) {
if (!$buttonUrl) {
if (strcmp('US', $code) === 0) {
$html[] = '<input type="image" name="submit" border="0" src="https://www.paypalobjects.com/' . $code4 . '/i/btn/' . $button . '.gif" alt="' . JText::_($this->textPrefix . '_BUTTON_ALT') . '">';
} else {
$html[] = '<input type="image" name="submit" border="0" src="https://www.paypalobjects.com/' . $code4 . '/' . $code . '/i/btn/' . $button . '.gif" alt="' . JText::_($this->textPrefix . '_BUTTON_ALT') . '">';
}
} else {
$html[] = '<input type="image" name="submit" border="0" src="' . $buttonUrl . '" alt="' . JText::_($this->textPrefix . '_BUTTON_ALT') . '">';
}
} else { // Default button
$html[] = '<input type="image" name="submit" border="0" src="https://www.paypalobjects.com/en_US/i/btn/' . $button . '.gif" alt="' . JText::_($this->textPrefix . '_BUTTON_ALT') . '">';
}
// Set locale
$html[] = '<input type="hidden" name="lc" value="' . $code . '" />';
}
/**
* Prepare a form element of payment receiver.
*
* #param $paymentReceiverOption
* #param $itemId
*
* #return null|string
*/
protected function preparePaymentReceiver($paymentReceiverOption, $itemId)
{
if ($this->params->get('paypal_sandbox', 1)) {
return '<input type="hidden" name="business" value="' . trim($this->params->get('paypal_sandbox_business_name')) . '" />';
} else {
if (strcmp('site_owner', $paymentReceiverOption) === 0) { // Site owner
return '<input type="hidden" name="business" value="' . trim($this->params->get('paypal_business_name')) . '" />';
} else {
if (!JComponentHelper::isEnabled('com_crowdfundingfinance')) {
return null;
} else {
$payout = new Crowdfundingfinance\Payout(JFactory::getDbo());
$payout->load(array('project_id' => $itemId));
if (!$payout->getPaypalEmail()) {
return null;
}
return '<input type="hidden" name="business" value="' . trim($payout->getPaypalEmail()) . '" />';
}
}
}
}
/**
* Return payment receiver.
*
* #param $paymentReceiverOption
* #param $itemId
*
* #return null|string
*/
protected function getPaymentReceiver($paymentReceiverOption, $itemId)
{
if ($this->params->get('paypal_sandbox', 1)) {
return strtolower(trim($this->params->get('paypal_sandbox_business_name')));
} else {
if (strcmp('site_owner', $paymentReceiverOption) === 0) { // Site owner
return strtolower(trim($this->params->get('paypal_business_name')));
} else {
if (!JComponentHelper::isEnabled('com_crowdfundingfinance')) {
return null;
} else {
$payout = new Crowdfundingfinance\Payout(JFactory::getDbo());
$payout->load(array('project_id' => $itemId));
if (!$payout->getPaypalEmail()) {
return null;
}
return strtolower(trim($payout->getPaypalEmail()));
}
}
}
}
}

I guess the problem lies here
$paymentReceiverOption = $this->params->get('paypal_payment_receiver', 'site_owner');
There must be some plugin settings at the backend that overrides any change you do in the code. Suppose that plugin params are stored with different data then only that data will be considered, even if you change it to project_owner.
Can you send more details of that plugin, plugin name, plugin parameters and also I feel you can write the post variables to a text file before being submitted, to know exactly where the problem lies.
You are probably using ITPrism Crowdfunding plugin. There if you see the XML file, you get this code
<?xml version="1.0" encoding="utf-8"?>
<extension version="3.6" type="plugin" group="crowdfundingpayment" method="upgrade">
<name>PLG_CROWDFUNDINGPAYMENT_PAYPAL</name>
<author>Todor Iliev</author>
<copyright>Copyright (C) 2016 Todor Iliev ( ITPrism.com ). All rights reserved.</copyright>
<license>http://www.gnu.org/licenses/gpl-3.0.en.html GNU/GPLv3</license>
<authorEmail>todor#itprism.com</authorEmail>
<authorUrl>http://itprism.com</authorUrl>
<version>2.5.3</version>
<creationDate>09 November, 2016</creationDate>
<description><![CDATA[
<p>Crowdfunding Payment - PayPal is a plugin that provides ability for making payments via PayPal Payments Standard method.</p>
<p><a href='http://itprism.com/' target='_blank'>Subscribe for the newsletter</a> to receive information about updates and new ITPrism extensions.</p>
<p>Please, <a href='http://extensions.joomla.org/extensions/extension/e-commerce/donations/crowdfunding' target='_blank'>vote for the extension</a> on Joomla! Extensions Directory</p>
]]></description>
<help url="PLG_CROWDFUNDINGPAYMENT_PAYPAL_HELP_URL"/>
<files>
<filename plugin="paypal">paypal.php</filename>
<folder>images</folder>
<folder>language</folder>
</files>
<config>
<fields name="params" addfieldpath="/administrator/components/com_crowdfunding/models/fields">
<fieldset name="basic">
<field name="paypal_business_name" type="text" size="80" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_MERCHANT_ID" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_MERCHANT_ID_DESC" />
<field name="paypal_url" type="text" size="80" default="https://www.paypal.com/cgi-bin/webscr" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_PAYPAL_URL" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_PAYPAL_URL_DESC" class="span6" />
<field name="return_url" type="text" size="80" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_RETURN_URL" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_RETURN_URL_DESC" class="span6" />
<field name="cancel_url" type="text" size="80" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_CANCEL_URL" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_CANCEL_URL_DESC" class="span6" />
<field name="callback_url" type="text" default="index.php?option=com_crowdfunding&task=notifier.notify&format=raw&payment_service=paypal" size="80" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_NOTIFY_URL" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_NOTIFY_URL_DESC" class="span6" />
<field name="paypal_country" type="cfcountries" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_COUNTRY" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_COUNTRY_DESC" required="true" />
</fieldset>
<fieldset name="sandbox" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_SANDBOX">
<field name="paypal_sandbox" type="radio" default="1" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_ENABLE_SANDBOX" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_SANDBOX_DESC" class="btn-group">
<option value="0">JNO</option>
<option value="1">JYES</option>
</field>
<field name="paypal_sandbox_business_name" size="80" type="text" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_SANDBOX_MERCHANT_ID" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_SANDBOX_MERCHANT_ID_DESC" />
<field name="paypal_sandbox_url" type="text" size="80" default="https://www.sandbox.paypal.com/cgi-bin/webscr" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_SANDBOX_URL" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_SANDBOX_URL_DESC" class="span6" />
</fieldset>
<fieldset name="emails" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_NOTIFICATION_EMAILS" addfieldpath="/administrator/components/com_emailtemplates/models/fields">
<field name="admin_mail_id" type="emailtemplate" default="0" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_SEND_MAIL_ADMIN" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_SEND_MAIL_ADMIN_DESC" class="btn-group" />
<field name="creator_mail_id" type="emailtemplate" default="0" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_SEND_MAIL_CREATOR" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_SEND_MAIL_CREATOR_DESC" class="btn-group" />
<field name="user_mail_id" type="emailtemplate" default="0" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_SEND_MAIL_USER" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_SEND_MAIL_USER_DESC" class="btn-group" />
<field name="email_mode" type="list" default="html" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_EMAIL_MODE" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_EMAIL_MODE_DESC" >
<option value="plain">PLG_CROWDFUNDINGPAYMENT_PAYPAL_PLAIN</option>
<option value="html">PLG_CROWDFUNDINGPAYMENT_PAYPAL_HTML</option>
</field>
</fieldset>
<fieldset name="advanced">
<field name="paypal_image_url" type="text" default="" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_LOGO_URL" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_LOGO_URL_DESC" size="80" class="span6" />
<field name="paypal_button_default" type="radio" default="0" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_DEFAULT_BUTTON" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_DEFAULT_BUTTON_DESC" class="btn-group">
<option value="0">JNO</option>
<option value="1">JYES</option>
</field>
<field name="paypal_button_type" type="list" default="html" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_BUTTON_TYPE" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_BUTTON_TYPE_DESC" >
<option value="btn_buynow_LG">PLG_CROWDFUNDINGPAYMENT_PAYPAL_BUY_NOW</option>
<option value="btn_buynowCC_LG">PLG_CROWDFUNDINGPAYMENT_PAYPAL_BUY_NOW_CC</option>
<option value="btn_paynow_LG">PLG_CROWDFUNDINGPAYMENT_PAYPAL_PAY_NOW</option>
<option value="btn_paynowCC_LG">PLG_CROWDFUNDINGPAYMENT_PAYPAL_PAY_NOW_CC</option>
<option value="btn_donate_LG">PLG_CROWDFUNDINGPAYMENT_PAYPAL_DONATE</option>
<option value="btn_donateCC_LG">PLG_CROWDFUNDINGPAYMENT_PAYPAL_DONATE_CC</option>
</field>
<field name="paypal_button_url" type="text" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_BUTTON_URL" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_BUTTON_URL_DESC" class="span6" size="80" />
<field name="paypal_load_certificate" type="radio" default="0" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_LOAD_CERTIFICATE" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_LOAD_CERTIFICATE_DESC" class="btn-group">
<option value="0">JNO</option>
<option value="1">JYES</option>
</field>
<field name="paypal_payment_receiver" type="list" default="site_owner" label="PLG_CROWDFUNDINGPAYMENT_PAYPAL_PAYMENT_RECEIVER" description="PLG_CROWDFUNDINGPAYMENT_PAYPAL_PAYMENT_RECEIVER_DESC">
<option value="site_owner">PLG_CROWDFUNDINGPAYMENT_PAYPAL_SITE_OWNER</option>
<option value="project_owner">PLG_CROWDFUNDINGPAYMENT_PAYPAL_PROJECT_OWNER</option>
</field>
</fieldset>
</fields>
</config>
</extension>
If you look at the end field there is paypal_payment_receiver. This is the setting to be entered at the backend. Login to your administrator and then open plugin manager. Search for paypal crowdfunding plugin. Set the parameter to project owner. Remember I am not asking you to change the code. This is more easy than changing your code.

Related

Login change in to signup

I have created a HTML5 registration form,is it possible for it to check the email address(inserted first) if it's already used to ask only for password(login) and if it's not to insert other fields needed for signup? using php,js or others.
<form id="signin_student" class="form-signin" method="post">
<h3 class="form-signin-heading"><i class="icon-lock"></i> Register </h3>
<input type="text" class="input-block-level" id="username" name="username" placeholder="NISN" required>
<input type="text" class="input-block-level" id="firstname" name="firstname" placeholder="Nama Depan" required>
<input type="text" class="input-block-level" id="lastname" name="lastname" placeholder="Nama Belakang" required>
<label>Kelas</label>
<select name="class_id" class="input-block-level span5">
<option>Pilih Kelas</option>
<?php
$query = mysql_query("select * from class order by class_name ")or die(mysql_error());
while($row = mysql_fetch_array($query)){
?>
<option value="<?php echo $row['class_id']; ?>"><?php echo $row['class_name']; ?></option>
<?php
}
?>
</select>
<input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
<input type="password" class="input-block-level" id="cpassword" name="cpassword" placeholder="Tulis Ulang Password" required>
<button title="Klik untuk Daftar" id="signin" name="login" class="btn btn-info" type="submit"><i class="icon-check icon-large"></i> Daftar</button>
</form>
<script>
jQuery(document).ready(function(){
jQuery("#signin_student").submit(function(e){
e.preventDefault();
var password = jQuery('#password').val();
var cpassword = jQuery('#cpassword').val();
if (password == cpassword){
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "student_signup.php",
data: formData,
success: function(html){
if(html=='true')
{
var delay = 2000;
setTimeout(function(){ window.location = 'siswa/index.php' }, delay);
}else if(html=='false'){
{ header: 'Data in DB is Not Found' });
}
}
});
}else
{
$.jGrowl("student does not found in the database", { header: 'Sign Up Failed' });
}
});
});
</script>
and file signup.php
<?php
mysql_select_db('db',mysql_connect('localhost','root',''))or die(mysql_error());
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$class_id = $_POST['class_id'];
$query = mysql_query("select * from student where username='$username' and firstname='$firstname' and lastname='$lastname' and class_id = '$class_id'")or die(mysql_error());
$row = mysql_fetch_array($query);
$id = $row['student_id'];
$count = mysql_num_rows($query);
if ($count > 0){
mysql_query("update student set password = '$password', status = 'Registered' where student_id = '$id'")or die(mysql_error());
$_SESSION['id']=$id;
echo 'true';
}else{
echo 'false';
}
?>
Firstly, you could use this code to check when the user stops typing:
Run javascript function when user finishes typing instead of on key up?
Once that is finished, this SQL code may work to check if the email already exists:
SELECT EXISTS(SELECT email FROM email_table)
Then you can simply use a conditional statement to print whether the email exists.

Form validation making field required

I'm a newbie here, I'm working on a registration form and trying to figure out why I can't make the "Name" field be required. Email and everything else seems to work fine. What am I missing?
Thx
this is what I have for the signup.js
$(document).ready(function() {
$("#signup-form").submit(function(e){
e.preventDefault();
var $form = $(this),
name = $form.find('input[name="name"]').val(),
email = $form.find('input[name="email"]').val(),
url = $form.attr('action');
$.post(url, {name:name, email:email},
function(data) {
if(data)
{
if(data=="Some fields are missing.")
{
$("#status").text("Please fill in your name and email.");
$("#status").css("color", "red");
}
else if(data=="Invalid name.")
{
$("#status").text("Please fill in your name.");
$("#status").css("color", "red");
}
else if(data=="Invalid email address.")
{
$("#status").text("Please check your email address.");
$("#status").css("color", "red");
}
else if(data=="Invalid list ID.")
{
$("#status").text("Your list ID is invalid.");
$("#status").css("color", "red");
}
else if(data=="Already subscribed.")
{
$("#status").text("You're already subscribed!");
$("#status").css("color", "red");
}
else
{
$("#status").text("You're subscribed! Please check your email for confirmation.");
$("#status").css("color", "green");
}
}
else
{
alert("Sorry, unable to subscribe. Please try again later!");
}
}
);
});
});
html file has this:
<form action="signup.php" method="POST" accept-charset="utf-8" name="signup-form" id="signup-form" class="sign_form" >
<label for="Silver">Get Notified</label>
<div>
<input type="text" name="name" value="" placeholder="Full Name" class="name" />
<input type="text" name="email" value="" placeholder="Email" class="email" />
<input type="submit" value="➜" id="submit-btn" class="submit" />
</div>
<label id="status"></label>
</form>
and the signup.php file is:
<?php
$submit_url = 'http://www.domain.com/signup';
$list = 'list010101';
//POST variables
$name = $_POST['name'];
$email = $_POST['email'];
//subscribe
$postdata = http_build_query(
array(
'name' => $name,
'email' => $email,
'list' => $list,
'boolean' => 'true'
)
);
$opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata));
$context = stream_context_create($opts);
$result = file_get_contents($submit_url.'/subscribe', false, $context);
echo $result;
?>
I think you should validate before you post because it seems you are posting to the server then checking the values. It's a good idea to validate before you send data to the server.
Something like:
$("#signup-form").submit(function(e){
e.preventDefault();
//use ids to find the form field e.g. <input type='text' id='name'>
var name = $("#name").val();
var email = $("#email").val();
//this is just checking if its an empty string, add your own validation here
if (email == "") return false;
if (name == "") return false;
//return true if validation passes for the form to submit or do your ajax post here
return true;
You could also use this plugin jquery validation

Create Button in last page pagination codeigniter

Hello there I have problem
I wanna create button in my pagination codeIgniter just in last page for submit form
here my code:
Controller:
function index() {
/* pagination config */
$this->load->library('pagination');
$config['base_url'] = site_url('dcm/index');
$config['per_page'] = 6;
$config['num_link'] = 5;
$config['next_link'] = 'Next';
$config['prev_link'] = 'Prev' ;
$config['total_rows'] = $this->db->get('soal')->num_rows();
/* this my form still have problem but I have different post for this one */
/* if you have any Idea for this please check my Question */
$data['form_action'] = site_url('dcm/index');
$jawab = $this->input->post('jawab');
$id_soal = $this->input->post('id_soal');
$this->dcm_model->inputJawab();
/* */
/* pagination setting */
$this->pagination->initialize($config);
$data['query'] = $this->db->get('soal', $config['per_page'], $this->uri->segment(3));
$data['link'] = $this->pagination->create_links();
$this->load->view('dcm/soal', $data);
}
in view:
<form action="<?php echo $form_action; ?>">
<?php foreach($query->result() as $row) { ?>
<?php echo $row->id_soal . '. ' . $row->soal; ?>
<input type="checkbox" checked="checked" value="<?=$row->id_soal;?>" name="jawab[]" />
<?php } ?>
<?php echo $link; ?>
</form>
<input align="center" type="submit" value="selesai" />
You can check if you are on the last page with this code:
if($this->pagination->cur_page >=
ceil($this->pagination->total_rows / $this->pagination->per_page))
{
$isLastPage = true;
}
else
{
$isLastPage = false;
}
You can pass the $isLastPage variable to your view.

PayPal IPN and PDT - Cannot get buyer postal address on return_url page or email

I am setting up a basic donation system and need to send a confirmation email to the client but cannot get the buyer postal address to show on return_url page of the website, or to show in the email to send to the client. The custom values for the taxpayer yes/no radio selects won't follow through either in the email. I am using a custom form on our website with fields to fill in the donation amount, name, address and if they pay tax (simple radio select.) Not sure if I'm using it right but I have both IPN and PDT settings on the site site and setup within the PayPal account.
Donation Form:
<form class="dsForm" name="details" action="https://www.paypal.com/cgi-bin/webscr" method="post" onsubmit="if ( !CheckForm() ) return false;">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" id="business" name="business" value="charityemail#internet.com">
<input type="hidden" id="item_name" name="item_name" value="Website Donation - Water">
<input type="hidden" name="notify_url" value="http://www.urltoipnscript.com/ipn.php">
<input type="hidden" id="item_number" name="item_number" value="3">
<input type="hidden" name="no_note" value="1">
<input type="hidden" id="currency_code" name="currency_code" value="GBP">
<input type="hidden" name="no_shipping" value="2">
<input type="hidden" name="tax" value="0">
<input type="hidden" name="bn" value="IC_Sample">
<input type="hidden" value="donation" name="custom">
<ul id="donate-form">
<li><label>Amount:</label>
<input type="text" id="amount" name="amount" value="25.00" size='9'>
<select id='currency' onchange='CheckCurrency()'>
<option value="GBP">GBP</option>
<option value="EUR">EUR</option>
<option value="AUD">AUD</option>
<option value="USD">USD</option>
</select>
</li>
<li><label>Program:</label>
<select name='program' id='program' onchange='ProgramChange();' >
<option value=''>Please Select</option>
<option id="education" value='4'>Education</option>
<option id="water" value='3' selected="selected">Water</option>
<option id="health" value='2'>Health Promotion</option>
<option id="community" value='18'>Community Based Projects</option>
<option id="sponsorship" value='8'>Child Sponsorship</option>
</select>
</li>
<li><label>Firstname:</label>
<input type='text' name='first_name' size='30' />
</li>
<li><label>Surname:</label>
<input type='text' name='last_name' size='30' />
</li>
<li><label>Address 1:</label>
<input type='text' name='address1' size='30' />
</li>
<li><label>Address 2:</label>
<input type='text' name='address2' size='30' />
</li>
<li><label>Town/City:</label>
<input type='text' name='city' size='30' />
</li>
<li><label>Postcode/Zip:</label>
<input type='text' name='zip' size='30' />
</li>
<li><label>Country:</label>
<select name='country' id='country' >
<option value='' selected='selected'>Please Select</option>
<option value='AL'>Albania
</option><option value='DZ'>Algeria
</option><option value='GB'>United Kingdom
</option><option value='US'>United States
etc...
</li>
<div id='ukTaxOptions' style='display:none'>
<label style="width:auto; margin-top:20px; margin-bottom:10px;font-weight: bold;" > Please choose an appropriate option below:</label >
<li>
<label style="width:auto" >
<input id='gbTaxPayer_1' name='gbTaxPayer_radio' type='radio' value='1' onchange="SetPayPalCustom('UK')" />
<input id="gbTaxPayer" name="gbTaxPayer" type="hidden" value="1" /> I am a UK taxpayer and would like to Gift Aid all donations I have made to Fields Of Life in the last four years and all donations I make in the future, until I notify you otherwise *
</label>
</li>
<li><label style="width:auto">
<input id='gbTaxPayer_' name='gbTaxPayer_radio' type='radio' value='' checked onchange="SetPayPalCustom('')" />I am not a UK taxpayer
</label></li>
<li><label style="width:auto">* I understand that I must have paid an amount of income tax or capital gains tax at least equal to the tax you reclaim on my donations</label></li>
</div>
<input type="hidden" name="hosted_button_id" value="hidden from stackflow">
<input type="image" src="http://www.hiddenfromsov.com/mybtn.png" border="0" name="submit" alt="PayPal — The safer, easier way to pay online.">
<li><img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif width="1" height="1" /></li>
</ul>
IPN Script:
<?php
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
if( !($res = curl_exec($ch)) ) {
curl_close($ch);
exit;
}
curl_close($ch);
if (strcmp ($res, "VERIFIED") == 0) {
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
$address_street = $_POST['address_street'];
$address_city = $_POST['address_city'];
$address_state = $_POST['address_state'];
$address_zip = $_POST['address_zip'];
$address_country = $_POST['address_country'];
$address_status = $_POST['address_status'];
$gbtax = $_POST['gbTaxPayer_radio'];
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
Code on success return_url page
//PDT
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';
$tx_token = $_GET['tx'];
$auth_token = "I've copied this the paypal settings";
$req .= "&tx=$tx_token&at=$auth_token";
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
// $fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
// read the body data
$res = '';
$headerdone = false;
while (!feof($fp)) {
$line = fgets ($fp, 1024);
if (strcmp($line, "\r\n") == 0) {
// read the header
$headerdone = true;
}
else if ($headerdone)
{
// header has been read. now read the contents
$res .= $line;
}
}
// parse the data
$lines = explode("\n", $res);
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0) {
for ($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
$item_number = $_GET['item_number'];
$address12 = $_GET['address_street'];
$firstname = $keyarray['first_name'];
$lastname = $keyarray['last_name'];
$payer_email = $keyarray['payer_email'];
$amount = $keyarray['mc_gross'];
$payment_date = $keyarray['payment_date'];
$payment_status = $keyarray['payment_status'];
$payment_type = $keyarray['payment_type'];
$mc_currency = $keyarray['mc_currency'];
$transactionid = $keyarray['txn_id'];
$itemname = $keyarray['item_name'];
$address1 = $keyarray['address1'];
$address_street = $keyarray['address_street'];
$address_city = $keyarray['address_city'];
$address_state = $keyarray['address_state'];
$address_zip = $keyarray['address_zip'];
$address_country = $keyarray['address_country'];
$gbtax = $keyarray['gbTaxPayer_radio'];
echo ("<p><strong>Payment Details</strong></p>\n");
echo ("<ul>\n");
echo ("<li><b>Address</b>: $address12</li>\n");
echo ("<li><b>Item Number</b>: $item_number</li>\n");
echo ("<li><b>Donation Type</b>: $itemname</li>\n");
echo ("<li><b>Date</b>: $payment_date</li>\n");
echo ("<li><b>Name</b>: $firstname $lastname ($payer_email)</li>\n");
echo ("<li><b>Street Address</b>: $address1</li>\n");
echo ("<li><b>Town/City</b>: $address_city</li>\n");
echo ("<li><b>County/State</b>: $address_state</li>\n");
echo ("<li><b>Postcode/ZIP</b>: $address_zip</li>\n");
echo ("<li><b>Country</b>: $address_country</li>\n");
echo ("<li><b>Amount</b>: £$amount</li>\n");
echo ("<li><b>Payment status</b>: $payment_status</li>\n");
echo ("<li><b>Transaction ID</b>: $transactionid</li>\n");
echo ("<li><b>UK Tax Payer?</b> $gbtax</li>\n");
echo ("</ul>\n");
// send e-mail
$today = date("F j, Y, g:i a");
mail("charityemail#internet.com", "Donation made - $itemname", "A donation was made on $today \n Payment Details \r\n\r\n Donation type: $itemname \r\n\r\n Name: $firstname $lastname \n Amount: $amount \n Donator Email: $payer_email \r\n\r\n Address: $address1 \n $address_city \n $address_state \n $address_zip \n $address_country \r\n\r\n Payment date: $payment_date \n Payment status: $payment_status \n Currency: $mc_currency \n Transaction ID: $transactionid \n UK Tax Payer? $gbtax \n", "From: Charity Donation <charityemail#internet.com>");
}
else if (strcmp ($lines[0], "FAIL") == 0) {
// log for manual investigation
}
}
fclose ($fp);
At the moment all I need to get working is the address to show on the email, return_url page and PayPal website (currently says Postal Address: Not Specified.)
Are you entering in an address when testing? Try passing over the variable "no_shipping" and setting the value to "2", and see if this makes a difference. Also PayPal will not pass back variables/values that are not valid PayPal variables, meaning you would not be able to make up your own variables and pass them over.

dynamically load form in codeigniter

I am new to codeigniter trying out some simple pages. I have successfully connected to the database for inserting and updating. But now I want to populate the fields from the database for updating. That is when the user selects the name from the dropdown the corresponding values should appear in the other fields so that the user can update easily.
I have worked on this to do without ajax or jquery. It worked for me but with some warning message - Use of undefined constant.
I am giving by mvc. Help me clear this.
Controller:
public function update()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Update Type';
$data['product_type'] = $this->editType_model->get_product_type();
$data['row'] = $this->editType_model->get_row();
$this->form_validation->set_rules('productype', 'productype', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('cm/update', $data);
$this->load->view('templates/footer');
}
else
{
$data['title']= 'Updation';
$data['message']= 'Updation succeeded';
$this->editType_model->update_news();
$this->load->view('cm/success', $data);
}
}
Model:
public function get_product_type() {
$data = array();
$this->db->order_by("product_type_name", "desc");
$query = $this->db->get('product_type');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function get_row() {
$data = array();
$id= $_POST[product_type_id];
$query = $this->db->get_where('product_type', array('product_type_id' => $id));
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function update_news()
{
$this->load->helper('date');
$Product = $this->input->post('product_type_id');
$data = array(
'product_type_name'=>($_POST['productype']),
'rank'=>($_POST['rank'])
);
$this->db->where('product_type_id',$Product);
return $this->db->update('product_type', $data);
}
View:
<?php $productType = 0;
if(isset($_POST['product_type_id'])){
$productType = $_POST['product_type_id'];
}?>
<div id="Content"><div>
<form action="" method="post" name="f1">
<table ><tr><td>Select Product Type Name:</td>
<td><Select id="product_type_id" name="product_type_id" onChange="document.f1.submit()">
<option value="0">--SELECT</option>
<?php if (count($product_type)) {
foreach ($product_type as $list) { ?>
<option value="<?php echo $list['product_type_id']; ?>"
<?php if($productType==$list['product_type_id']) echo "Selected" ?> >
<?php echo $list['product_type_name']; ?></option>
<?php }} ?></Select></td></tr></table></form>
<?php if($productType){
if (count($row)) {
foreach ($row as $faProductType) { ?>
<div > <form action="" method="post" class="form-Fields" >
<input type="hidden" name="product_type_id" id="product_type_id" value="<?php echo $faProductType['product_type_id']; ?>" >
<table border="0" cellpadding="8" cellspacing="0" >
<tr><td>Product Type <font color="red">*</font></td><td style="width: 10px;"> : </td>
<td><input name="productype" type="text" value="<?php echo $faProductType['product_type_name']; ?>" style=" width:300px;" /></td>
<td><span class="err" id="productTypeDesc1Err"></span></td></tr>
<tr><td >Rank</td><td style="width:10px;"> : </td>
<td ><input type="text" name="rank" id="rank" value="<?php echo $faProductType['rank']; ?>" size="39" /> <span class="err" id="productTypeNameErr"></span></td>
<td ></td></tr><tr><td></td><Td colspan="2" align="center">
<input type="submit" value="Update" class="buttonimg" name='cm/editType/update' style="width:100px"
onClick="return validEditProductType();">
</Td><td></td></tr></table></form></div></div></div>
<?php }}} ?>
you can use Ajax for this purpose
onchange of your select box fill a div with form.
Controller Method
function getUserdata(){
$where['username'] = $this->input->post('username');
$this->load->model('users_model');
$data['user'] = $this->users_model->getUser($where);
$this->load->view('userform',$data);
}
And you model method
function getUser($where){
return $this->db->where($where)->get('usertable')->row()
}
Ajax
$(function(){
$('#selecttion').change(function(){
var username = $(this).val();
$.ajax({
url : '<?php 'echo url to controller method'?>',
type : 'POST' ,
data : 'username='+username,
success : function(data){
$('#dividtofill').html(data);
}
});
});
})
EDIT :
calling ajax is easy
for this include jquery library in your header.
Here is your dropdown
Note : put the above ajax code in your head section in script
<select name="user" id="selecttion">
<option value="John">John</option>
<option value="Sam">Sam</option>
<option value="David">David</option>
</select>
Now when this dropdown value is changed the ajax function defined above will be called.
I have finally cleared the error. I have done this by a simple if isset loop.
Now my get_row() in my model looks like this.
public function get_row() {
$data = array();
$id= 0;
if(isset($_POST['product_type_id'])){
$id = $_POST['product_type_id'];
}
$query = $this->db->get_where('product_type', array('product_type_id' => $id));
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}