Screen Shot of HTML Form.
Can you suggest me where am I doing mistakes in my Laravel app, each time i am uploading multiple files throug the form, files is uploading perfectly in given location, but only 1 records are being inserted into database table. Here is my code...
// Upload bg_certificateArr photo
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
initialize $ac_bg for every foreach loop.
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
$ac_bg = new AccountBankGuarantee; // like this
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
You haven't posted full code here, but I believe before loop you somehow set $ac_bg variable. So looking at your code you create one record and update it in every next loop iteration.
So to fix this you should probably do something like this:
foreach ($request->file('bg_certificate') as $key => $file) {
$ac = new Ac(); // don't know what's the exact model class here
Then in every loop iteration you will create new record instead of updating it.
I created a webservice, it works correctly, I was doing the node creation operation and it works correctly.
I need to validate the node I'm about to save in the same way it is validated during the interface insertion form.
I have tried with
drupal_form_submit($nodeType . '_node_form', $form_state, (object) $node);
it keeps giving me errors its node reference fields
Could you suggest other ways to do the same validation that is done by the interface on a programmatically created node?
The error on the node reference field is:
" field_ente : this entry cannot be
referenced. "
The node (6310) exists correctly and if I try to do the node_save, it is saved correctly
the complete function is as follows
function my_ws_resource_create($field_nome = '', $field_cognome = '', $field_codice_fiscale = '', $field_data_di_nascita = '', $field_ente= '')
{
module_load_include('inc', 'node', 'node.pages');
global $user;
$nodeType = 'contatti';
$node = new stdClass();
$node->type = $nodeType;
$node->uid = $user->uid;
$node->status = 1;
$node->revision = 1;
$node->promote = 0;
$node->comment = 0;
node_object_prepare($node);
$node->field_cognome['und'][0]['value'] = $field_cognome;
$node->field_nome['und'][0]['value'] = $field_nome;
$node->field_codice_fiscale['und'][0]['cck_codicefiscale'] = $field_codice_fiscale;
$node->field_data_di_nascita['und'][0]['value'] = $field_data_di_nascita;
$node->field_categoria_contatto['und'][0]['tid'] = '66';
// $node->field_ente = array('und' => array(array('nid'=> $field_ente )));
// this field causes the error
$node->field_ente = array('und' => array(array('nid'=> '6310')));
$node->field_simplenews_term['it'][0]['tid'] = '13660';
$form_state = array();
$form_state['values']['type'] = $nodeType;
$form_state['values']['name'] = $user->name;
$form_state['values']['status'] = 1;
$form_state['values']['promote'] = 1;
$form_state['values']['sticky'] = 0;
$form_state['values']['op'] = t('Save');
drupal_form_submit($nodeType . '_node_form', $form_state, (object) $node);
if ($errors = form_get_errors()) {
return services_error(implode(" ", $errors), 406, array('form_errors' => $errors));
}
return 'Creation successful';
}
I've had success with the following (remove $form_state and replace drupal_form_submit):
if ($node = node_submit($node)) {
node_save($node);
// Success!
}
else {
// Fail :(
}
What I want to do is When I enter all my information (for client ID 199 in the picture) In my account being submit it, it goes into the database. BUT I want it to change to something and so i added an if statement
Here the code im adding to the existing code already at the BOTTOM of the code
if ($vpr_clid == 199) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
if the ($vpr_clid = 199)
i want the clname to be "Shelley Madsen And Associates" then what is show in the table below instead of "Nice and White Smiles" (that an example of the results look like)
but when i chcek the database it not changing it and still show "Nice and White Smiles :(
I dont see any error, so it might be the placement of the code i have to put the IF statement in the huge php file? Dont know how to fix this issue
Thanks (the code below is the base code before i added the If statement)
I also insert the if statement before the function were called but still didnt work example
if ($vpr_clid == 199) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
$result = InsertIntoPayReminder($link, $vars);
$result = GetVpr_Id($link, $vars);
<?php
session_start();
if ($_SESSION['company'] != "ACB") {
// redirect to the logout page
$redirect = 'logout.php';
include './includes/redirect.php';
}
class variables_obj {
var $vpr_plan = '';
var $vpr_id = '';
var $vpr_clid = '';
var $vpr_cl_name = '';
var $vpr_cl_phone = '';
var $vpr_call_start_date = '';
var $vpr_db_account = '';
var $vpr_db_fname = '';
var $vpr_db_mname = '';
var $vpr_db_lname = '';
var $vpr_rp_fname = '';
var $vpr_rp_mname = '';
var $vpr_rp_lname = '';
var $vpr_rp_address = '';
var $vpr_rp_city = '';
var $vpr_rp_state = '';
var $vpr_rp_zipcode = '';
var $vpr_rp_phonenum = '';
var $vpr_rp_phonetype = '';
var $vpr_date_entered = '';
var $newrecdt = '';
var $vpl_day_offset = '';
var $vpl_action = '';
var $vpr_promocode = '';
}
function ScrubPhone($old_phone_num) {
$phone_length = strlen($old_phone_num);
$new_phone_num = "";
for($i = 0; $i < $phone_length; $i = $i + 1) {
if(is_numeric($old_phone_num[$i])) {
$new_phone_num .= $old_phone_num[$i];
}
}
return $new_phone_num;
}
function ScheduleCreated($link, $vars) {
$query = "UPDATE v_payreminder SET vpr_schedule_created = '1' WHERE vpr_id='".$vars->vpr_id."'";
if (!mysql_query($query,$link)) {
die('Error: ' . mysql_error());
}
return true;
}
function CreateScheduleRow($link, $vars){
// echo "vpl_day_offset: ".$vars->vpl_day_offset."<br>";
// echo "vpl_action: ".$vars->vpl_action."<br>";
$plus_days = " +".$vars->vpl_day_offset." days";
// echo "plus days: ".$plus_days."<br>";
$date_offset = strtotime(date("Y-m-d", strtotime($vars->vpr_date_entered)).$plus_days);
$date_offset = date("Y-m-d", $date_offset);
// echo "date_offset: ".$date_offset."<br>";
// $date_offset = strtotime(date("Y-m-d",strtotime($vars->vpr_date_entered))." +".$vars->vpl_day_offset." days");
// $date_offset = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");
// echo "date_offset: ".$date_offset."<br>";
$query = "INSERT INTO v_pr_schedule (
vpr_id,
vsc_plan,
vsc_date_entered,
vsc_action,
vsc_action_date,
vsc_status
) VALUES (
'$vars->vpr_id',
'$vars->vpr_plan',
'$vars->vpr_date_entered',
'$vars->vpl_action',
'$date_offset',
'VACT')";
//echo "query: ".$query."<br>";
if (!mysql_query($query,$link)) {
die('Error: ' . mysql_error());
}
return true;
}
function CreateSchedule($link, &$vars) {
// CREATE SCHEDULE
$query = " SELECT vpl_day_offset, vpl_action, vpl_condition
FROM v_plan
WHERE vpl_plan = '".$vars->vpr_plan."'";
// echo "query: ".$query."<br>";
$qresult = mysql_query($query);
if (!$qresult) {
print(mysql_error());
}
if ($qresult && mysql_num_rows($qresult) > 0 ) {
while ($row = mysql_fetch_array($qresult, MYSQL_ASSOC)) {
$vars->vpl_day_offset = $row['vpl_day_offset'];
$vars->vpl_action = $row['vpl_action'];
if ($row['vpl_condition'] == 'OO') {
CreateScheduleRow($link, $vars);
}
}
}
return true;
}
function InsertIntoPayReminder($link, &$vars) {
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
//echo "Client Name: ".$vars->vpr_cl_name."<br><br>";
//exit();
$sql="INSERT INTO v_payreminder (
vpr_clid,
vpr_cl_name,
vpr_cl_phone,
vpr_call_start_date,
vpr_db_account,
vpr_db_fname,
vpr_db_mname,
vpr_db_lname,
vpr_rp_fname,
vpr_rp_mname,
vpr_rp_lname,
vpr_rp_phonenum,
vpr_rp_phonetype,
vpr_rp_address,
vpr_rp_city,
vpr_rp_state,
vpr_rp_zipcode,
vpr_promo,
vpr_date_entered) VALUES (
'$vars->vpr_clid',
'$vars->vpr_cl_name',
'$vars->vpr_cl_phone',
'$vars->vpr_call_start_date',
'$vars->vpr_db_account',
'$vars->vpr_db_fname',
'$vars->vpr_db_mname',
'$vars->vpr_db_lname',
'$vars->vpr_rp_fname',
'$vars->vpr_rp_mname',
'$vars->vpr_rp_lname',
'$vars->vpr_rp_phonenum',
'$vars->vpr_rp_phonetype',
'$vars->vpr_rp_address',
'$vars->vpr_rp_city',
'$vars->vpr_rp_state',
'$vars->vpr_rp_zipcode',
'$vars->vpr_promocode',
'$vars->vpr_date_entered')";
if (!mysql_query($sql,$link)) {
die('Error2: ' . mysql_error());
}
return true;
}
function GetVpr_Id($link, &$vars) {
// Find out what vpr_id is
$query = "SELECT vpr_id FROM v_payreminder ";
$query .= "WHERE vpr_clid = '".$vars->vpr_clid."' AND vpr_date_entered = '".$vars->vpr_date_entered."'";
$qresult = mysql_query($query);
if (!$qresult) {
print(mysql_error());
}
if ($qresult && mysql_num_rows($qresult) > 0 ) {
$row = mysql_fetch_array($qresult, MYSQL_ASSOC);
$vars->vpr_id = $row['vpr_id'];
}
}
function InsertInActivity($link, $vars) {
// ENTER INTO ACTIVITY
$vaction_desc = 'PATIENT ENTERED';
$sql = "INSERT INTO v_pr_activity (
vpr_id,
va_plan,
va_action_dttm,
va_action_code,
va_action_desc,
va_disposition_code,
va_disposition_desc,
va_status_code,
va_status_desc
) VALUES (
'$vars->vpr_id',
'$vars->vpr_plan',
'$vars->vpr_date_entered',
'VINIT',
'$vaction_desc',
'SUCCESS',
'SUCCESS',
'VACT',
'ACTIVE'
)";
if (!mysql_query($sql,$link)) {
die('Error: ' . mysql_error());
}
}
include './includes/dblogin.php';
$vars = new variables_obj();
$vars->vpr_plan = 'VP01';
$vars->vpr_clid = $_SESSION['userid'];
//-------------------------------------------------------
// No commas can be in client name or they will
// mess up the Global Connect CSV file.
//-------------------------------------------------------
$vpr_cl_name = $_SESSION['username'];
$vpr_cl_name = str_replace(",", " ", $vpr_cl_name);
$vars->vpr_cl_name = $vpr_cl_name;
//-------------------------------------------------------
//-------------------------------------------------------
$vars->vpr_cl_phone = ScrubPhone($_SESSION['uphone']);
$vars->vpr_call_start_date = '0000-00-00';
$vars->vpr_db_account = $_POST['ndaccnum'];
$vars->vpr_db_fname = $_POST['ndfreqname'];
$vars->vpr_db_mname = $_POST['ndmname'];
$vars->vpr_db_lname = $_POST['ndlreqname'];
$vars->vpr_rp_fname = $_POST['ndrfreqname'];
$vars->vpr_rp_mname = $_POST['ndrmname'];
$vars->vpr_rp_lname = $_POST['ndrlreqname'];
$vars->vpr_rp_address = '';
$vars->vpr_rp_city = '';
$vars->vpr_rp_state = $_POST['ndrstatereqname'];
$vars->vpr_rp_zipcode = $_POST['ndrreqzipcode'];
$phonenumber = $_POST['1ndrreqphone'].$_POST['2ndrreqphone'].$_POST['3ndrreqphone'];
$vars->vpr_rp_phonenum = $phonenumber;
$vars->vpr_rp_phonetype = $_POST['treqphone'];
$vars->vpr_date_entered = date('Y-m-d H:i:s');
$vars->newrecdt = date('Ymd');
$vars->vpr_promocode = $_POST['promocode'];
// echo "vpr_plan: ".$vars->vpr_plan."<br>";
// echo "vpr_date_entered: ".$vars->vpr_date_entered."<br>";
// echo "newrecdt: ".$vars->newrecdt."<br>";
// echo "vpr_clid: ".$vars->vpr_clid."<br>";
// echo "vpr_id: ".$vars->vpr_id."<br>";
$result = InsertIntoPayReminder($link, $vars);
$result = GetVpr_Id($link, $vars);
$result = InsertInActivity($link, $vars);
$result = CreateSchedule($link, $vars);
$result = ScheduleCreated($link, $vars);
// echo "vpr_id: ".$vars->vpr_id."<br>";
mysql_close($link);
// redirect
$redirect = 'vpayremind.php';
include './includes/redirect.php';
?>
okay referencing the following lines..
if ( $vpr_clid == 199 ) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
$result = InsertIntoPayReminder($link, $vars);
...and then:
function InsertIntoPayReminder($link, &$vars) {
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
so on and so forth... }
it doesnt seem as if you are actually setting the value of the class object. You seem to be setting some arbitrary php variable to the name you want, and then passing a totally different ' $vars ' object into the function. I don't see any reason to believe that the ' $vars ' you are passing into the function call contains the name value you want it to contain. You should be assigning the value of ' $vars ' before passing it in.
For instance:
if ( $vpr_clid == 199 ) {
$vars[ 'vpr_cl_name' ] = "Shelley Madsen And Associates";
}
then you can get rid of this line all together:
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
Here is register new user code in php laravel-5.4 mysql
public function store(Request $request)
{
$epincheck = $request->epin;
if (Epin::where('epin', '=', '75656565')->exists()) {
// DB::table('epins')->where('epin', $epincheck)->delete();
$post = new Admin();
$post->name = $request->name;
$post->email = $request->email;
$post->plan = $request->plan;
$post->epin = $epincheck;
$post->ref = $request->ref;
$post->mobile = $request->mobile;
$post->password = bcrypt($request->password);
$post->save();
//other trims
$referal_user = $request->ref;
$referal_email = DB::table('admins')->where('mobile', $referal_user)->first();
$referal_id = $referal_email->id;
$update_ref_user = Admin::find($referal_id);
$previous_users_left = $referal_email->user_left;
$previous_users_right = $referal_email->user_right;
$direct_referal = $referal_email->direct_referal;
$list_all_right_user = $referal_email->user_listing_right;
$list_all_left_user = $referal_email->user_listing_left;
$left_count = $referal_email->no_user_left;
$right_count = $referal_email->no_user_right;
$direct_count = $referal_email->no_direct_referal;
if(!$previous_users_right && $previous_users_left )
{
$update_ref_user->user_right = $request->email ;
$update_ref_user->no_user_right = $right_count+1 ;
$update_ref_user->user_listing_right = $request->email . ' , ' . $list_all_right_user ;
$update_ref_user->save();
$last_updated_id = $update_ref_user->id;
$update_up_line = DB::table('admins')->where('id', $last_updated_id);
$update_up_line_list = $update_up_line->id;
// $update_up_line = Admin::find($last_updated_id);
/* $update_up_line_update->user_listing_right = $request->email;
$update_up_line-> save();*/
//looping get referal id -> find referee -> update ;
//find last referal id -> find referee -> update ;
//find referal id -> find referee -> update ;
//find referal id -> find referee -> update ;
//find referal id -> find referee -> update ;
//when there is no ref_no loop ends
//stop when count ends;
}
if(!$previous_users_left)
{
$update_ref_user->user_left = $request->email ;
$update_ref_user->no_user_left = $left_count + 1 ;
$update_ref_user->user_listing_left = $request->email . ' , ' . $list_all_left_user ;
$update_ref_user->save();
}
if($previous_users_left && $previous_users_right)
{
$update_ref_user->direct_referal = $direct_referal . ' , ' . $request->email ;
$update_ref_user->no_direct_referal = $direct_count +1 ;
$update_ref_user->save();
}
//sms gatewat
/*Send SMS using PHP*/
return redirect('/admin/login');
// \Session::flash('msg', 'Changes Saved.' );
}
else {
echo "You Have Entered Invalid Pin";
}
}
When a new user is registered he inputs reference code in signup form.
I want that when a new user is registered with mobile->'123' and reference number '987' then
step 1) find "reference number" of new registered user then search "reference number" in "mobile" field of all registered user then add 50% of $200(it is currency)to his income add previous user's name in a database field name="user_under"
step 2) find "reference number" of previous user then search "reference number" in "mobile" field of all registered user then add 30% of $200(it is currency)to his income add previous user's name in a database field name="user_under"
step 3) find "reference number" of previous user then search "reference number" in "mobile" field of all registered user then add 10% of $200(it is currency) to his income and add previous user's name in a database field name="user_under"
step 4) find "reference number" of previous user then search "reference number" in "mobile" field of all registered user then add previous user's name in a database field name="user_under"
******step 4 continues till reference number= null/ no value
I cannot understand how to apply the logic
#####edit
#jeffrey
here is manual code for 5th level need to automate it using while recursive
public function store(Request $request)
{
$post = new Admin();
$post->name = 'nill';
$post->email = $request->email;
$post->plan = 'uuiuii';
$post->epin = '9999';
$post->ref = $request->ref;
$post->mobile = $request->mobile;
$post->password = bcrypt($request->password);
$post->save();
$referal_user = $request->ref;
$referal_email = DB::table('admins')->where('mobile', $referal_user)->first();
$referal_id = $referal_email->id;
$right_count = $referal_email->no_user_right;
$list_all_right_user = $referal_email->user_listing_right;
//first update
$update_ref_user = Admin::find($referal_id);
$get_user_previous = $referal_email->user_listing_right;
$update_ref_user->user_right = $request->email;
$update_ref_user->no_user_right = $right_count + 1;
$update_ref_user->user_listing_right = $request->email . ' , ' . $get_user_previous;
$update_ref_user->save();
$last_updated_id = $update_ref_user->ref;
///next
///
// echo $last_updated_id;
$ref_previous2 = $last_updated_id;
if($ref_previous2 ) {
$referal_email2 = DB::table('admins')->where('mobile', $last_updated_id)->first();
$get_user_previous2 = $referal_email2->user_listing_right;
$update_ref_user_id_2 = $referal_email2->id;
$update_ref_user2 = Admin::find($update_ref_user_id_2);
$update_ref_user2->user_right = 'jhkkkj';
$update_ref_user2->no_user_right = $right_count + 1;
$update_ref_user2->user_listing_right = $request->email . ' , ' . $get_user_previous2;
$update_ref_user2->save();
$ref_previous3 = $update_ref_user2->ref;
if($ref_previous3 ) {
$last_updated_id3 = $update_ref_user2->ref;
$referal_email3 = DB::table('admins')->where('mobile', $last_updated_id3)->first();
$get_user_previous3 = $referal_email3->user_listing_right;
$update_ref_user_id_3 = $referal_email3->id;
$update_ref_user3 = Admin::find($update_ref_user_id_3);
$update_ref_user3->user_right = 'jhkkkj';
$update_ref_user3->no_user_right = $right_count + 1;
$update_ref_user3->user_listing_right = $request->email . ' , ' . $get_user_previous3;
$update_ref_user3->save();
$ref_previous4 = $update_ref_user3->ref;
if($ref_previous4 ) {
$last_updated_id4 = $update_ref_user3->ref;
$referal_email4 = DB::table('admins')->where('mobile', $last_updated_id4)->first();
$get_user_previous4 = $referal_email4->user_listing_right;
$update_ref_user_id_4 = $referal_email4->id;
$update_ref_user4 = Admin::find($update_ref_user_id_4);
$update_ref_user4->user_right = 'jhkkkj';
$update_ref_user4->no_user_right = $right_count + 1;
$update_ref_user4->user_listing_right = $request->email . ' , ' . $get_user_previous4;
$update_ref_user4->save();
$ref_previous5 = $update_ref_user4->ref;
if($ref_previous5 ) {
$last_updated_id5 = $update_ref_user4->ref;
$referal_email5 = DB::table('admins')->where('mobile', $last_updated_id5)->first();
$get_user_previous5 = $referal_email5->user_listing_right;
$update_ref_user_id_5 = $referal_email4->id;
$update_ref_user5 = Admin::find($update_ref_user_id_5);
$update_ref_user5->user_right = 'jhkkkj';
$update_ref_user5->no_user_right = $right_count + 1;
$update_ref_user5->user_listing_right = $request->email . ' , ' . $get_user_previous5;
$update_ref_user5->save();
}
}
}
}
//next
//4th update
///five
///
///
return redirect('/admin/register2');
}
#############here is the solution
$referal_user = $request->ref;
$referal_email = DB::table('admins')->where('mobile', $referal_user)->first();
$referal_id = $referal_email->id;
$right_count = $referal_email->no_user_right;
$list_all_right_user = $referal_email->user_listing_right;
$ref = $request->ref;
$mobile = $request->mobile;
$user_listing_left = $referal_email->user_listing_left;
while( $refUser = Admin::where('mobile', $ref)->first() )
{
$refUser->user_left = $request->email;
$refUser->user_listing_left = $refUser->user_listing_left . "," .$request->email;
$refUser->save();
// Update $ref to find the next guy
$ref = $refUser->ref;
}
I don't understand the question fully, but I'll give it a shot.
Recursive is the key word here. You seem to want to go up the tree of reference, and depending on what level you are, add a certain amount of $ to that person. I do however not understand what you mean by add previous user's name in a database field name="user_under" the field is not visible as well...
$percentages = [50, 30, 10, 5, 2, 1, 0.5];
$iteration = 0;
$ref = $request->ref;
while( $refUser = Admin::where('ref', $ref)->first() && $percentages[$iteration] )
{
$refUser->income += floor( 200 * $percentages[$iteration++] );
$refUser->save();
// Update $ref to find the next guy
$ref = $refUser->ref;
}
The second condition for the while loop, is to make sure that if the $percentages array is shorted than the tree in the database, it won't break and quits giving money. You may of course extend the array.
I hope this is what you asked, else leave a comment.
Assuming I try to save the following data and the Songs model's name attribute has a Phalcon\Mvc\Model\Validator\PresenceOf validator set on it
// Get an existing artist
$artist = Artists::findFirst('name = "Shinichi Osawa"');
// Create an album
$album = new Albums();
$album->name = 'The One';
$album->artist = $artist;
$songs = array();
// Create a first song
$songs[0] = new Songs();
$songs[0]->name = 'Star Guitar';
$songs[0]->duration = '5:54';
// Create a second song
$songs[1] = new Songs();
$songs[1]->name = '';
$songs[1]->duration = '4:29';
// Assign the songs array
$album->songs = $songs;
// Save the album + its songs
if (!$album->save()) {
foreach ($album->getMessages() as $message) {
$message->getModel(); // this returns null since model is new
}
}
I will get an error message saying that 'name' is required.
Question: is there a built in way of getting the related model on which the error occurred (in this case $songs[1]), or at least the alias/index of the error model (in this case songs/1)?
Didn't find a built-in solution but came up with this.
Base model
public function beforeValidation()
{
$session = $this->getService('session');
if (!$session->has('model:validation')) {
$validation = $indexes = [];
} else {
$modelName = get_called_class();
$validation = $session->get('model:validation');
if (!isset($validation[$modelName])) {
$validation[$modelName] = 0;
$indexes = $session->get('model:validation:relationIndex');
$indexes[] = $modelName;
} else {
$validation[$modelName]++;
// reset child indexes
$indexes = $session->get('model:validation:relationIndex');
$modelIndex = array_search($modelName, $indexes);
for ($i = $modelIndex + 1; $i < count($indexes); $i++) {
$modelName = $indexes[$i];
unset($validation[$modelName]);
unset($indexes[$i]);
}
$indexes = array_values($indexes);
}
}
$session->set('model:validation:relationIndex', $indexes);
$session->set('model:validation', $validation);
}
Controller
$session = $this->getDI()->get('session');
$session->remove('model:validation');
$session->remove('model:validation:relationIndex');
if (!$this->save()) {
var_dump($session->get('model:validation:relationIndex'));
var_dump($session->get('model:validation'));
}