Contactform 7 cant set hidden value - php

I am trying to implement the Paypal payment gateway once the contact form is submitted.
For that I am storing the form data in db and retrieving data from the saved id once payment is completed. Saving that db id in hidden field for sending to paypal url.
I have tried and values are returned. But when I getting form data in wpcf7mailsent it is empty.
function action_wpcf7_submit( $array ) {
global $wpdb;
$wpcf7 = WPCF7_ContactForm::get_current();
$form_id = $wpcf7->id;
$submission = WPCF7_Submission::get_instance();
$invalid_fields = $submission->get_invalid_fields();
$posted_data = $submission->get_posted_data();
if ($form_id ==123 && empty($invalid_fields))
{
$first_name = $posted_data['first-name'];
$last_name = $posted_data['last-name'];
$parent_email = $posted_data['parent-email'];
$parent_phone = $posted_data['parent-phone'];
$duration = $posted_data['Duration'][0];
$total_price = $posted_data['total_price'];
$notes_requests = $posted_data['notes-requests'];
$studentcount = $posted_data['studentcount'];
$table_name = "store_subscription";
$result_check = $wpdb->insert($table_name, array('parent_guardian_firstname' => $first_name, 'parent_guardian_lastname' => $last_name, 'parent_guardian_email' => $parent_email,'parent_guardian_phone' => $parent_phone, 'subscription_duration' => $duration, 'total_price' => $total_price, 'notes_special_request' => $notes_requests) );
$lastid = $wpdb->insert_id;
if($result_check){
for($i=1;$i<=$studentcount;$i++){
$add_student_name = $posted_data['student_name_'.$i];
$add_current_grade_level = $posted_data['current_grade_level_'.$i];
$additional_student_table = "store_subscription_student";
if(!empty($add_student_name)){
$wpdb->insert($additional_student_table, array('store_subscription_id'=> $lastid, 'student_name' => $add_student_name, 'grade_level' => $add_current_grade_level));
}
}
//setting the store_subscriptin_id to retrieve the data from the paypal.
$posted_data['store_subscription_id'] = $lastid;
$posted_data['paypal_pg_redirect_url'] = "https://www.example.com/redirect-paypal/?id=$lastid&amt=$total_price";
return $posted_data;
}
}
}
add_filter( 'wpcf7_submit', 'action_wpcf7_submit');
add_action( 'wp_footer', 'mycustom_wp_footer' );
function mycustom_wp_footer() {
?>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( e ) {
console.log(e.detail);
if ( '123' == e.detail.contactFormId ) {
var paypal_pg_redirect_url = document.getElementById('paypal_pg_redirect_url').value;
console.log(paypal_pg_redirect_url);
///window.location.href = paypal_pg_redirect_url;
}
}, false );
</script>
<?php
}
The hidden field value is not set. Can someone help me to set the hidden field value and retrieve in wpcf7mailsent
Note: I have tried hook before_send_mail, later came to know that we cant change the value in before_send_mail. So then I tried posted_data hook also the value not set to hidden field. store_subscription_id is the hidden field I am trying to set value. Pls help.

Maybe try adding if(isset()) before setting the value:
if(isset($lastid)){
$posted_data['store_subscription_id'] = $lastid;
}

Related

WordPress contact form 7 text value change

WordPress - Contact Form 7
I am trying to find out the filter to modify the cf7 field value when someone enter values in it.
when user type in textfield and submit data,
validate - I had done
should not goto thank you page if invalid entry - I had done
replace text field with new data - Not Done
Eg: 1
add_filter( 'wpcf7_validate_text*', 'your_validation_filter_func_tel', 100, 2 );
function your_validation_filter_func_tel( $result, $tag ) {
$Yourvalue = $_POST['your-number'];
if ( strlen( $Yourvalue ) == 2 ) {
$result->invalidate( 'your-number', "Please enter a valid number. " . );
// HERE I WANT TO REPLACE NEW DATA TO TEXT FIELD
$result->data( 'your-number', '1002' );
} else if ( strlen( $Yourvalue ) == 3 ) {
$result->invalidate( 'your-number', "Please enter a valid name." . );
// HERE I WANT TO REPLACE NEW DATA TO TEXT FIELD
$result->data( 'your-number', '1003' );
}
return $result;
}
Eg: 2
another working example
everything working except $result['tel'] = $tel_cleaned_final;
<?php
function custom_filter_wpcf7_is_tel( $result, $tel )
{
// Initialization and Clean Input
$tel_cleaned = strtr( $tel, array(' '=>'', '-'=>'', '.'=>''));
$tel_cleaned_trimmed = ltrim(strtr( $tel_cleaned, array('+'=>'')), '0');
/* Test Conditions.
I concluded 3 if conditions to 1 below bcaz the validation is working perfect
*/
if ('test conditions here')
$tel_cleaned_final = substr($tel_cleaned_trimmed, 2);
else
$tel_cleaned_final = $tel_cleaned_trimmed;
if (strlen($tel_cleaned_final) == 10)
{
$result = true;
//$result['tel'] = $tel_cleaned_final;
/*
Here i want to return new number to text box
for eg: +91 98989-89898 returns 9898989898
*/
}
else
{
$result = false;
}
return $result;
}
add_filter( 'wpcf7_is_tel', 'custom_filter_wpcf7_is_tel', 10, 2 );
?>
What you are trying to do cannot be done with only the validation filter. Because that just outputs true or false based on the validations performed. To do what you want, you have to use another filter ( 'wpcf7_posted_data' ) that has the value you want to filter. So we can break down our process into two steps.
Step 1: Do all the validation like you are currently doing.
Using your Example 2.
function custom_filter_wpcf7_is_tel( $result, $tel )
{
// Initialization and Clean Input
$tel_cleaned = strtr( $tel, array(' '=>'', '-'=>'', '.'=>''));
$tel_cleaned_trimmed = ltrim(strtr( $tel_cleaned, array('+'=>'')), '0');
/* Test Conditions.
I concluded 3 if conditions to 1 below bcaz the validation is working perfect
*/
if ('test conditions here')
$tel_cleaned_final = substr($tel_cleaned_trimmed, 2);
else
$tel_cleaned_final = $tel_cleaned_trimmed;
if (strlen($tel_cleaned_final) == 10)
{
$result = true;
} else
{
$result = false;
}
return $result;
}
add_filter( 'wpcf7_is_tel', 'custom_filter_wpcf7_is_tel', 10, 2 );
The above code will make sure that your points 1 and 2 are working.
Validate.
Stop submission if entry is invalid.
Step 2: Re-run your tests to get the desired value and update it.
function sr_change_updated_field_value( $posted_data )
{
// Initialization and Clean Input
$tel_cleaned = strtr( $tel, array(' '=>'', '-'=>'', '.'=>''));
$tel_cleaned_trimmed = ltrim(strtr( $tel_cleaned, array('+'=>'')), '0');
/* Test Conditions.
I concluded 3 if conditions to 1 below bcaz the validation is working perfect
*/
if ('test conditions here')
$tel_cleaned_final = substr($tel_cleaned_trimmed, 2);
else
$tel_cleaned_final = $tel_cleaned_trimmed;
// Use the name of your field in place of "tel"
$posted_data['tel'] = $tel_cleaned_final;
return $posted_data;
};
add_filter( 'wpcf7_posted_data', 'sr_change_updated_field_value', 10, 1 );
P.S. This will update the values sent in the email, or in the submissions if you store them. It will show the validation message, but it will not show the updated value in text field because that cannot be done with php in this scenario.
P.S. 2 This is all tested code. Happy Coding.
maybe this can help:
add_action( 'wpcf7_before_send_mail', 'some_function_name', 1 );
function some_function_name( $contact_form ) {
$wpcf7 = WPCF7_ContactForm::get_current();
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$data = array();
$data['posted_data'] = $submission->get_posted_data();
$firstName = $data['posted_data']['first-name']; // just enter the field name here
$mail = $wpcf7->prop('mail');
if($firstName =''){
$mail['body'] = str_replace('[first-name]', $firstName . '-blah blah', $mail['body']);
}
$wpcf7->set_properties(array(
"mail" => $mail
));
return $wpcf7;
}
}
Hope it helps!
P.S. This is not tested, please let me know if it works :)

Q: How to store the results of a calculation into a hidden field

We have a gravity form in 4 parts.
1. Input an Australian postcode
2. Select swimming pool dimensions
3. Select accessories
4. Show quotation, prompt for contact details.
In functions.php we have defined a few global symbols. $PostCode is set to the value of the postcode value that is entered on page 1. Once $PostCode is > 0 we include a php file. This file contains a large array of freight charges indexed by the postcode. The postcode-specific charges are transferred to hidden fields on page 2 of the form and are used for later calculations.
Along with the freight charges is a formula. This formula is evaluated using data from the hidden fields on page 2 and also from a number field on page 2 that calculates the pool area from entry fields of length and width.
The result of the evaluation of the formula should be entered into a field on page 3 for use in other calculations. It is at this point that a problem is encountered, namely that the receiving hidden field is not updated.
Code:
// global symbols
$Formula1 = '';
$TNTFreightPrices = array();
$FieldNumberContent = array();
$PostCode = '';
$Formula1Result = 0;
add_filter('gform_field_input_11', 'update_hidden', 10, 5);
function update_hidden($input, $field, $value, $lead_id, $form_id)
{
global $TNTFreightPrices, $FieldNumberContent, $Formula1, $PostCode, $Formula1Result;
$pgno = $field['pageNumber'];
$PostCode = rgpost("input_3");
if (!empty($PostCode)) {
$path = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/tntfreightprices/TNTFreightPrices.php';
$tmp = include_once $path;
if (gettype($tmp) == "array") {
$TNTFreightPrices = $tmp['postcodes'];
$Formula1 = $tmp['Formula1'];
$f = $form_id;
$BasicChrg = $TNTFreightPrices[$PostCode]['BasicChrg'];
$KgChrg = $TNTFreightPrices[$PostCode]['KgChrg'];
$MinChrg = $TNTFreightPrices[$PostCode]['MinChrg'];
$RemotAreaChrg = $TNTFreightPrices[$PostCode]['RemotAreaChrg'];
$ResidChrg = $TNTFreightPrices[$PostCode]['ResidChrg'];
$_0to15Chrg = $TNTFreightPrices[$PostCode]['0to15Chrg'];
$_15to199Chrg = $TNTFreightPrices[$PostCode]['15to199Chrg'];
$_200to299Chrg = $TNTFreightPrices[$PostCode]['200to299Chrg'];
$_300to399Chrg = $TNTFreightPrices[$PostCode]['300to399Chrg'];
$_400to499Chrg = $TNTFreightPrices[$PostCode]['400to499Chrg'];
$_500to599Chrg = $TNTFreightPrices[$PostCode]['500to599Chrg'];
$_600plusChrg = $TNTFreightPrices[$PostCode]['600plusChrg'];
$FuelSurchrg = $TNTFreightPrices[$PostCode]['FuelSurchrg'];
$FieldNumberContent = array(
'85' => Content_tag(
"input", "",
array(
"id" => "input_{$f}_85",
"class" => "gform_hidden",
"name" => "input_85",
"aria-invalid" => "false",
"value" => "$BasicChrg",
"type" => "hidden")
),
// ...
The Content_tag function is not shown. It generates HTML to set the value of the hidden fields on page 2. An example of its output is
input id="input_11_85" class="gform_hidden" name="input_85" aria-invalid="false" value="9.33" type="hidden">
These values are stored in the $FieldNumberContent array and are returned to the caller depending on the field_id, viz
$fid = $field['id'];
if (array_key_exists($fid, $FieldNumberContent)) {
$input = $FieldNumberContent[$fid];
}
The update_hidden function ends with
return $input;
}
The next block of code takes the values of the hidden fields on page 2 and the result of the area calculation, also on page 2 and replaces the matching values in the formula stored in $Formula1, finally eval'ing the string and storing its result in the global $Formula1Result.
add_filter('gform_field_value', 'populate_fields_into_formula1', 10, 3);
function populate_fields_into_formula1( $value, $field, $name )
{
global $Formula1, $PostCode, $TNTFreightPrices, $Formula1Result;
if (array_key_exists($PostCode, $TNTFreightPrices) ) {
$fid = $field['id'];
if (strpos($Formula1, "[") !== false) {
$sym = "[{$field['label']}]";
$val = rgpost("input_{$fid}");
$Formula1 = str_replace($sym, $val, $Formula1);
} else {
$f1 = "return {$Formula1};";
$f1 = str_replace(",", "", $f1);
$Formula1Result = eval($f1);
}
}
return $value;
}
An example formula is
[AreaCalculator]/2 * [KgChrg] >= [MinChrg] ? [AreaCalculator]/2 * [KgChrg] : [MinChrg]
Finally here's the code that is supposed to updating the field hidden field on page 3. We clicked the checkbox allowing the field to be updated dynamically and gave the parameter name as formula1result.
add_filter('gform_field_value_formula1result', 'populate_formula1result', 10, 3);
function populate_formula1result($value, $field, $name)
{
global $Formula1Result;
if ($Formula1Result > 0) {
$value = $Formula1Result;
}
return $value;
}
Now I confess up front that I am not a particularly adept PHP programmer. Perhaps there is a better way of doing all this, and believe me I am all ears.
But I've been metaphorically hitting my head against this for a day or more. Everything else appears to be working. It's only this that's not Why?

Codeigniter Get New Generated Username From Model To Controller

I have been struggling on this issue for a very long time and I still do not have any idea how to get this working.
Currently I need to show my new generated username from Model to Controller. But I can't seem to call it. Below is my code:
Model formval_callbacks.php :
public function _username_check( $user_name )
{
$this->db->select('user_name');
$this->db->like('user_name', $user_name);
$this->db->order_by('user_date', 'desc');
$this->db->limit(1);
$query = $this->db->get('users');
if ($query->num_rows() > 0)
{
$row = $query->row();
$db_username = $row->user_name;
$username_counter = preg_match("/".$user_name."(\d+)/", $db_username, $matches) ? (int)$matches[1] : NULL;
$username_counter++;
return $user_name.$username_counter;
}else{
$username_counter = 1;
return $user_name.$username_counter;
}
}
Model user_model.php :
public function create_user( $role, $insert_array = array() )
{
// The form validation class doesn't allow for multiple config files, so we do it the old fashion way
$this->config->load( 'form_validation/administration/create_user/create_' . $role );
$this->validation_rules = config_item( $role . '_creation_rules' );
// If the data is already validated, there's no reason to do it again
if( ! empty( $insert_array ) OR $this->validate() === TRUE )
{
// Prepare user_data array for insert into user table
$user_data = array(
'user_name' => ( isset( $insert_array['user_name'] ) ) ? $insert_array['user_name'] : set_value('user_name'),
'user_pass' => ( isset( $insert_array['user_pass'] ) ) ? $insert_array['user_pass'] : set_value('user_pass'),
'user_email' => ( isset( $insert_array['user_email'] ) ) ? $insert_array['user_email'] : set_value('user_email')
);
// User level derived directly from the role argument
$user_data['user_level'] = $this->authentication->levels[$role];
// If we are using form validation for the user creation
if( empty( $insert_array ) )
{
// Remove some user_data elements from _field_data array as prep for insert into profile table
$this->form_validation->unset_field_data( array(
'user_name',
'user_pass',
'user_email'
));
// Create array of profile data
foreach( $this->form_validation->get_field_data() as $k => $v )
{
$profile_data[$k] = $v['postdata'];
}
// Unset all data for set_value(), so we can create another user
$this->kill_set_value();
}
// If we are not using form validation for the user creation
else
{
// Remove some insert_array elements as prep for insert into profile table
unset( $insert_array['user_name'] );
unset( $insert_array['user_pass'] );
unset( $insert_array['user_email'] );
// Profile data is insert array
$profile_data = $insert_array;
}
// Encrypt any sensitive data
if( isset( $profile_data['license_number'] ) )
{
$this->load->library('encrypt');
$profile_data['license_number'] = $this->encrypt->encode( $profile_data['license_number'] );
}
// Create a random user id if not already set
$random_unique_int = $this->get_unused_id();
// Generate random user salt
$user_salt = $this->authentication->random_salt();
// Perform transaction
$this->db->trans_start();
$user_data['user_id'] = $random_unique_int;
$user_data['user_pass'] = $this->authentication->hash_passwd( $user_data['user_pass'], $user_salt );
$user_data['user_salt'] = $user_salt;
$user_data['user_date'] = time();
$user_data['user_modified'] = time();
// Insert data in user table
$this->db->set($user_data)
->insert( config_item('user_table'));
$profile_data['user_id'] = $random_unique_int;
// Insert data in profile table
$this->db->set($profile_data)
->insert( config_item( $role . '_profiles_table'));
// Complete transaction
$this->db->trans_complete();
// Verify transaction was successful
if( $this->db->trans_status() !== FALSE )
{
// Load var to confirm user inserted into database
$this->load->vars( array( 'user_created' => 1 ) );
}
return TRUE;
}
return FALSE;
}
Controller register.php :
public function index()
{
// Load resources
$this->load->library('csrf');
$this->load->model('registration_model');
$reg_mode = $this->registration_model->get_reg_mode();
// Check to see if there was a registration submission
if( $this->csrf->token_match )
{
// If mode #1, registration allows for instant user creation without verification or approval.
if( $reg_mode == 1 )
{
$_POST['user_level'] = 1;
$this->load->model('user_model');
$this->user_model->create_user( 'customer', array() );
$this->load->model('formval_callbacks');
$view_data['new_username'] = $this->formval_callbacks->_username_check();
}
}
// If for some reason the user is already logged in
$this->is_logged_in();
// Send registration mode to view
$view_data['reg_mode'] = $reg_mode;
// Ouput alert-bar message if cookies not enabled
$this->check_cookies_enabled();
$data = array(
'title' => WEBSITE_NAME . ' - Account Registration',
'content' => $this->load->view( 'public/register/registration_form', $view_data, TRUE ),
// Load the show password script
'javascripts' => array(
'js/jquery.passwordToggle-1.1.js',
'js/jquery.char-limiter-3.0.0.js',
'js/default-char-limiters.js'
),
// Use the show password script
'extra_head' => '
<script>
$(document).ready(function(){
$("#show-password").passwordToggle({target:"#user_pass"});
});
</script>
'
);
$this->load->view( $this->template, $data );
}
There is an error for this line because I never put in any parameters :
$view_data['new_username'] = $this->formval_callbacks->_username_check();
What should I do if I just want to get the new generated username without putting in the parameter?
Also, is it better to get the new generated username from formval_callback.php or user_model.php in this function :
if( $this->db->trans_status() !== FALSE )
Hope you guys can help me out here.

Passing parameters to a function in yii

I am new to yii. I've created a custom in button in CGridView that has a class of CButtonColumn. I'm just wondering how can I pass parameters that I can add to my php function in my model.
This is my custom button in the table
array(
'class'=>'CButtonColumn',
'template'=>'{approve}, {update},{delete}',
'buttons'=>array(
'approve' => array(
'label'=>'Approve',
'options'=>array(),
'click'=>$model->approveRegistrants("$user_id, $category", array("id"=>$data->user_id , "category"=>$data->category),
)
)
)
and this is my function is
public function approveRegistrants($user_id, $category){
$db = new PDO('mysql:host=localhost; dbname=secret; charset=utf8', 'Andy', '*****');
$getCounter = "SELECT registrants FROM counter order by registrants desc limit 1;";
$bool = false;
$show = '0';
do{
$result = $db->query($getCounter);
// $registrants = $db->query($getCounter);
// $result->setFetchMode(PDO::FETCH_ASSOC);
// $registrants = '1';
foreach ($result as $value){
$registrants = $value['registrants'];
echo 'hello'.$registrants.'</br>';
}
// $registrants = $result['registrants'];
// print_r($registrants);
$max_registrants = '3400';
if($max_registrants > $registrants){
// pdo that will use $updateCounterByOne
$updateCounterByOne = "UPDATE counter set registrants = registrants + 1 WHERE registrants = ". $registrants .";";
$updateCounter = $db->prepare($updateCounterByOne);
$updateCounter->execute();
// return affected rows
$returnAffectedRows = $updateCounter->rowCount();
$bool = true;
// break;
}
else{
echo "No more slot Available";
// break;
}
}while($returnAffectedRows == '0');
if($bool = true){
//sql syntax
$selectApprovedUser = "SELECT user_id FROM registrants WHERE user_id = '". $user_id ."';";
//pdo that will use $selectApprovedUser
$updateApprovedUser = "UPDATE registrants set approved = 'YES' where user_id = ". $selectApprovedUser .";";
$updateApproved = $db->prepare($updateApprovedUser);
$updateApproved->execute();
//pdo that will use $insertApprovedUser
$insertApprovedUser = "INSERT INTO approved_registrants (user_id, category, approved_date) VALUES ('".$user_id."', '".$category."', 'curdate()');";
$insertApproved = $db->prepare($insertApprovedUser);
$insertApproved->execute();
//execute trial
$selectSomething = "SELECT registrants from counter where tandem = '0'";
$doSelect = $db->prepare($selectSomething);
$doSelect->execute();
$hello = $doSelect->fetchAll();
echo $hello[0]['registrants'];
}
}
your issue is that you are bypassing the controller fully here.
buttons column is configured with the following parameters
'buttonID' => array(
'label'=>'...', // text label of the button
'url'=>'...', // a PHP expression for generating the URL of the button
'imageUrl'=>'...', // image URL of the button. If not set or false, a text link is used
'options'=>array(...), // HTML options for the button tag
'click'=>'...', // a JS function to be invoked when the button is clicked
'visible'=>'...', // a PHP expression for determining whether the button is visible
)
See CButtonColumn for details.
As you can see click has to be a js function that will be called on clicking the button. You can rewrite your button like this
array(
'class'=>'CButtonColumn',
'template'=>'{approve}, {update},{delete}',
'buttons'=>array(
'approve' => array(
'label'=>'Approve',
'options'=>array(),
// Alternative -1 Url Method -> will cause page to change to approve/id
'url'=>'array("approve","id"=>$data->id)',
// Alternative -2 Js method -> use 1,2 not both
'click'=>'js:approve()',
)
)
)
in your CGridView configuration you add
array(
....
'id'=>'gridViewID', //Unique ID for grid view
'rowHtmlOptionsExpression'=> 'array("id"=>$data->id)',
)
so that each row has the unique ID, ( you can do the same to a button, but it slightly more difficult as $data is not available there)
in your js function you can do this.
<script type="text/javascript">
function approve(){
id = $(this).parent().parent().attr("id");
<?php echo CHtml::ajax(array( // You also can directly write your ajax
'url'=>array('approve'),
'type'=>'GET',
'dataType'=>'json',
'data'=>array('id'=>'js:id'),
'success'=>'js:function(json){
$.fn.yiiGridView.update("gridViewID",{});
// this will refresh the view, you do some other logic here like a confirmation box etc
}'
));?>
}
</script>
Finally your approve action
class YourController extend CController {
......
public function actionApprove(){
id = Yii::app()->request->getQuery('id');
$dataModel = MyModel::model()->findByPk($id); // This is the model has the $user_id, and $category
....
$OtherModel->approve($dataModel->user_id,$dataModel->category) // if approve is in the same model you can self reference the values of category and user_id directly no need to pass as parameters.
// Do some logic based on returned value of $otherModel->approve()
// return the values from the approve() function and echo from here if required back to the view, directly echoing output makes it difficult to debug which function and where values are coming from .
Yii::app()->end();
}

How to update the value of array in Yii session

I am using "ajaxSubmitButton" to send some values of 3 fields: registrant, product id and quantity to controller (controller name: actionCart). After submitting the button I receive those values in session array what I did successfully. At this point, if I submit same product id but different quantity, I want to update the quantity key with new value. I have done this by php global $_SESSION but can't using Yii session variable.
public function actionCart()
{
if(isset($_POST["Order"])){
$item = $_POST["Order"];
$registration_id = $item["registration_id"];
$this->productId = $item["item"];
$quantity = $item["quantity"];
$quantity = $item["quantity"]=='' ? 1 : $item["quantity"];
$productInfo = Products::model()->findByPk(array('id'=>$this->productId));
$totalPrice = $productInfo->price * $quantity;
$newItem = array("product_id" => $this->productId , "product_name" => $productInfo->name, "quantity" => $quantity,"price" => $productInfo->price,"totalPrice" => $totalPrice);
$session = Yii::app()->session;
$cartArray = $session['cart'];
$searchArrResult = $this->searchSubArray($session['cart'],'product_id',$this->productId);
if (!empty($searchArrResult)) {
/***** this works *****/
foreach ( $_SESSION['cart'] as $key=>$cart ) {
if ( $cart["product_id"] == $this->productId ) {
$_SESSION['cart'][$key]['quantity']=$quantity;
$_SESSION['cart'][$key]['totalPrice']=$totalPrice;
}
}
/***** following commented code does not work *****
*
foreach($session['cart'] as $key=>$cart){
if ($cart["product_id"] == $this->productId){
$session['cart'][$key]['quantity'] == $quantity;
$session['cart'][$key]['totalPrice'] == $totalPrice;
}
}*/
}
else {
$cartArray[] = $newItem;
$session['cart'] = $cartArray;
}
print_r($session['cart']);
//unset(Yii::app()->session['cart']);
}
}
In the above code I marked by commenting where I want to update session values. Please help me someone if it is possible do in yii.
Try this:
$carts = $session['cart'];
foreach($carts as $key=>&$cart){
if ($cart["product_id"] == $this->productId){
$cart['quantity'] == $quantity;
$cart['totalPrice'] == $totalPrice;
}
}
$session['cart'] = $carts;
Yii::app()->session return object of CHttpSession, not reference to $_SESSION.
$carts = $session['cart'] equals operation $carts = $session->get('cart'); (by means magic method __get in CHttpSession) and $session['cart'] = $carts; equals to $session->set('cart', $carts); (by __set)
That's why you can't setting by $session['cart'][$key]['quantity'] = $quantity;
UPDATED full solution (I change logic of saving products - $key = product_id)
public function actionCart()
{
if(isset($_POST["Order"])){
$item = $_POST["Order"];
$registration_id = $item["registration_id"];
$this->productId = $item["item"];
$quantity = empty(intval($item["quantity"])) ? 1 : intval($item["quantity"]);
$productInfo = Products::model()->findByPk(array('id'=>$this->productId));.
if(empty($productInfo))
return false; // or other action
$newItem = array(
"product_id" => $this->productId ,
"product_name" => $productInfo->name,
"quantity" => $quantity,
"price" => $productInfo->price,
"totalPrice" => ($productInfo->price * $quantity)
);
$cartArray = Yii::app()->session['cart'];
$cartArray[$this->productId] = $newItem;
Yii::app()->session['cart'] = $cartArray;
}
}

Categories