Opencart foreach showing NULL in tpl file - php

Am creating a custom module in my store using Opencart, that file name called sales_performance.
Here am passing the values for selected customer id and name.
All working fine. when am using var_dump($data['customers']); in controller it showing some values in top of the sales_performance.tpl.
But in sales_performance.tpl am using var_dump($customers); it showing NULL.
sales_performance.php(controller)
<?php
class ControllerProductSalesPerformance extends Controller
{
private $error = array();
public function index()
{
$this->load->language('product/allproduct');
$this->document->setTitle($this->language->get('Sales Performance'));
$this->load->model('catalog/allproduct');
$this->getSelectedCustomer();
$data['text_list'] = $this->language->get('text_list');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['text_confirm'] = $this->language->get('text_confirm');
$data['text_missing'] = $this->language->get('text_missing');
$data['column_order_id'] = $this->language->get('column_order_id');
$data['column_customer'] = $this->language->get('column_customer');
$data['column_status'] = $this->language->get('column_status');
$data['column_total'] = $this->language->get('column_total');
$data['column_date_added'] = $this->language->get('column_date_added');
$data['column_date_modified'] = $this->language->get('column_date_modified');
$data['column_action'] = $this->language->get('column_action');
$data['entry_return_id'] = $this->language->get('entry_return_id');
$data['entry_order_id'] = $this->language->get('entry_order_id');
$data['entry_customer'] = $this->language->get('entry_customer');
$data['entry_order_status'] = $this->language->get('entry_order_status');
$data['entry_total'] = $this->language->get('entry_total');
$data['entry_date_added'] = $this->language->get('entry_date_added');
$data['entry_date_modified'] = $this->language->get('entry_date_modified');
$data['button_invoice_print'] = $this->language->get('button_invoice_print');
$data['button_shipping_print'] = $this->language->get('button_shipping_print');
$data['button_add'] = $this->language->get('button_add');
$data['button_edit'] = $this->language->get('button_edit');
$data['button_delete'] = $this->language->get('button_delete');
$data['button_filter'] = $this->language->get('button_filter');
$data['button_view'] = $this->language->get('button_view');
//$data['token'] = $this->session->data['token'];
$pagination = new Pagination();
//$pagination->total = $order_total;
//$pagination->page = $page;
$data['pagination'] = $pagination->render();
$data['sort'] = $sort;
$data['order'] = $order;
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('default/template/product/sales_performance.tpl', $data));
}
public function getSelectedCustomer()
{
$isSalesPerson=$_COOKIE['isSalesPerson'];
if($isSalesPerson =='true')
{
$selectedCustomerId = $_GET['selectedCustomerId'];
$selectedCustomerName = $_GET['selectedCustomerName'];
}
//select customer
$customerId=$_COOKIE['customerId'];
$query = $this->db->query("select customer_id,CONCAT(c.firstname,' ', c.lastname) as name from " . DB_PREFIX . "customer c where c.sales_person_id=".$customerId." and customer_id=".$selectedCustomerId."");
$getcustomers=$query->rows;
foreach ($getcustomers as $customer) {
$data['customers'][] = array(
'customer_id' => $customer['customer_id'],
'name' => $customer['name']
);
}
var_dump($data['customers']); // this the code showing some value
//select customer
}
}
sales_performance.tpl
<?php var_dump($customers); ?>
<?php foreach ($customers as $customer) { ?>
<h3>Customer ID: <?php echo $customer['customer_id']; ?></h3>
<h3>Customer Name:</h3>
<?php } ?>
What am missed here...?
And Thanks for advance...

The data variable is a variable in your function, you are able to create a protected variable in your class and use that one.
<?php
class ControllerProductSalesPerformance extends Controller
{
private $error = array();
private $data = array();
public function index()
{
$this->load->language('product/allproduct');
$this->document->setTitle($this->language->get('Sales Performance'));
$this->load->model('catalog/allproduct');
$this->getSelectedCustomer();
$this->data['text_list'] = $this->language->get('text_list');
$this->data['text_no_results'] = $this->language->get('text_no_results');
$this->data['text_confirm'] = $this->language->get('text_confirm');
$this->data['text_missing'] = $this->language->get('text_missing');
$this->data['column_order_id'] = $this->language->get('column_order_id');
$this->data['column_customer'] = $this->language->get('column_customer');
$this->data['column_status'] = $this->language->get('column_status');
$this->data['column_total'] = $this->language->get('column_total');
$this->data['column_date_added'] = $this->language->get('column_date_added');
$this->data['column_date_modified'] = $this->language->get('column_date_modified');
$this->data['column_action'] = $this->language->get('column_action');
$this->data['entry_return_id'] = $this->language->get('entry_return_id');
$this->data['entry_order_id'] = $this->language->get('entry_order_id');
$this->data['entry_customer'] = $this->language->get('entry_customer');
$this->data['entry_order_status'] = $this->language->get('entry_order_status');
$this->data['entry_total'] = $this->language->get('entry_total');
$this->data['entry_date_added'] = $this->language->get('entry_date_added');
$this->data['entry_date_modified'] = $this->language->get('entry_date_modified');
$this->data['button_invoice_print'] = $this->language->get('button_invoice_print');
$this->data['button_shipping_print'] = $this->language->get('button_shipping_print');
$this->data['button_add'] = $this->language->get('button_add');
$this->data['button_edit'] = $this->language->get('button_edit');
$this->data['button_delete'] = $this->language->get('button_delete');
$this->data['button_filter'] = $this->language->get('button_filter');
$this->data['button_view'] = $this->language->get('button_view');
//$data['token'] = $this->session->data['token'];
$pagination = new Pagination();
//$pagination->total = $order_total;
//$pagination->page = $page;
$data['pagination'] = $pagination->render();
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['header'] = $this->load->controller('common/header');
$this->data['column_left'] = $this->load->controller('common/column_left');
$this->data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('default/template/product/sales_performance.tpl', $this->data));
}
public function getSelectedCustomer()
{
$isSalesPerson=$_COOKIE['isSalesPerson'];
if($isSalesPerson =='true')
{
$selectedCustomerId = $_GET['selectedCustomerId'];
$selectedCustomerName = $_GET['selectedCustomerName'];
}
//select customer
$customerId=$_COOKIE['customerId'];
$query = $this->db->query("select customer_id,CONCAT(c.firstname,' ', c.lastname) as name from " . DB_PREFIX . "customer c where c.sales_person_id=".$customerId." and customer_id=".$selectedCustomerId."");
$getcustomers=$query->rows;
foreach ($getcustomers as $customer) {
$this->data['customers'][] = array(
'customer_id' => $customer['customer_id'],
'name' => $customer['name']
);
}
var_dump($this->data['customers']); // this the code showing some value
//select customer
}
}
You are also able to let getSelectedCustomer() return an array with the customers, this would be the normal way to do it. I would recomment it to put it into a model as well.

Related

: Invalid argument supplied for foreach() in

tried this code on two different WordPress sites. It was working on the first site. After I moved the template completely to my new site, I got this error: Invalid argument supplied for foreach() in
I do not know what is the reason, although it is the same template, plugins and everything
<?php
$novoteste = new ComicLatestChapters("6", "6");
$resultados = $novoteste->filter;
foreach($resultados as $resultado => $novoteste) {
$series_id = $novoteste->post_id;
$status = get_post_status($series_id);
if($status !== 'publish' || $series_id == 20305){
continue;
}
$result = get_post($resultado);
$sort_by = $sort_setting['sortBy'];
$sort_order = $sort_setting['sort'];
$chapters = $wp_manga_functions->get_latest_chapters($series_id, null, 2, 0, $sort_by, $sort_order);
$latest_chapter = $chapters[0];
$semilatest_chapter = $chapters[1];
$scheduled1 = $latest_chapter['schedule_time'];
$scheduled2 = $semilatest_chapter['schedule_time'];
$series_link = get_the_permalink($series_id);
$chapter_slug1 = $latest_chapter['chapter_slug'];
$chapter_slug2 = $semilatest_chapter['chapter_slug'];
$type = $wp_manga_functions->get_manga_type( $manga_id );
$chapter_name1 = $latest_chapter['chapter_name'];
$chapter_name2 = $semilatest_chapter['chapter_name'];
$mass_released = is_mass_released($series_id);
$ch_1 = get_only_numbers($chapter_name1);
$ch_2 = get_only_numbers($chapter_name2);
$rating = get_post_meta($series_id, '_manga_avarage_reviews', true);
$chapter_index1 = $latest_chapter['chapter_index'];
$chapter_index2 = $semilatest_chapter['chapter_index'];
$link1 = $wp_manga_functions->build_chapter_url($series_id, $chapter_slug1);
$link2 = $wp_manga_functions->build_chapter_url($series_id, $chapter_slug2);
$restored = get_post_meta($series_id, 'restored', true);
$publish = $latest_chapter['date'];
$publish2 = $semilatest_chapter['date'];
$type = get_post_meta($series_id, '_wp_manga_chapter_type', true);
$series_status = get_post_meta($series_id, '_wp_manga_status', true);
if (isset($scheduled1)){
$published = $wp_manga_functions->get_time_diff($scheduled1);}
else{
$published = $wp_manga_functions->get_time_diff($publish);
}
if (isset($scheduled2)){
$published2 = $wp_manga_functions->get_time_diff($scheduled2);}
else{
$published2 = $wp_manga_functions->get_time_diff($publish2);
}
$series_class = get_post_meta($series_id, 'manga_custom_badges', true);
$class_css = str_replace(' ', '-', strtolower($series_class));
$novel1 = get_post($series_id);
$title = $novel1->post_title;
$description = $result->post_content;
$thumbnail_id = get_post_meta($series_id, '_thumbnail_id', true);
$thumbnail_link = get_the_post_thumbnail_url($series_id, array(290,395));
?>
You should check that the output $resultados = $novoteste->filter; Is it empty or not?
The code changes like this:
<?php
$novoteste = new ComicLatestChapters( "6", "6" );
$resultados = $novoteste->filter ?: array();
foreach( $resultados as $resultado => $novoteste ) {
........
}

How to Indent Laravel controller, view code?

One of my project needs code indentation, it has many of controller files looking like below code.
so basically I want to do is format code which should be done automatically without changing each file manually.
Controller code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
use File;
use Html;
use DB;
use Illuminate\Validation\Rule;
use Illuminate\Support\Str;
use Validator;
use Datatables;
use AppHelper;
use LaraCore;
use Image;
use App\Models\Customer;
use App\Models\_List;
use Carbon;
class CustomerController extends Controller
{
public function validator(array $data, $id = NULL)
{
$email_Rules = explode(',',"required,email,unique");
$email_Rules['unique'] = Rule::unique('customers')->ignore($id);
if(($key = array_search('unique',$email_Rules)) !== false) {
unset($email_Rules[$key]);
}
return Validator::make($data, [
'secret_key' => 'required|min:6|max:10',
'email' => $email_Rules,
'first_name' => 'required|alpha_num',
'city' => 'required',
]
);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('panel.customers.index');
}
public function create()
{
$data = array();
$EmployeeType = _List::where('list_name','=','EmployeeType')->pluck('item_name','id')->all();
$data['EmployeeType'] = $EmployeeType;
$Category = _List::where('list_name','=','Category')->pluck('item_name','id')->all();
$data['Category'] = $Category;
return view('panel.customers.create',$data);
}
public function edit($id,Request $request)
{
$data = array();
$Dates = array();
$customers = Customer::findOrFail($id);
$data['customers'] = $customers;
$EmployeeType = _List::where('list_name','=','EmployeeType')->pluck('item_name','id')->all();
$data['EmployeeType'] = $EmployeeType;
$preference= explode(',',$customers->preference);
$customers->preference = $preference;
$Category = _List::where('list_name','=','Category')->pluck('item_name','id')->all();
$data['Category'] = $Category;
if($customers->ready!=''){
$ready= explode(',',$customers->ready);
$customers->ready = $ready;
}
if($customers->approved!=''){
$approved= explode(',',$customers->approved);
$customers->approved = $approved;
}
$Name = explode(',','start_date,end_date');
$Dates[0] = new Carbon($customers->$Name[0]);
$Dates[1] = new Carbon($customers->$Name[1]);
$data['start_dateend_date'] = $Dates[0]->format('m/d/Y').' - '.$Dates[1]->format('m/d/Y') ;
return view('panel.customers.create',$data);
}
public function store(Request $request,$id="")
{
$this->validator($request->all(),$request->id)->validate();
if($request->id == null || $request->id == ""){
$inputs = $request->all();
if($request->has('secret_key')){
$secret_key = bcrypt($request->secret_key);
$inputs['secret_key'] = $secret_key;
}
if($request->has('preference')){
$preference = implode(',',$request->preference);
$inputs['preference'] = $preference;
}
if($request->has('ready')){
$ready = implode(',',$request->ready);
$inputs['ready'] = $ready;
}else{
$inputs['ready'] = "";
}
if($request->has('start_date,end_date')){
$Dates = explode('-',$request->input('start_date,end_date'));
$Name = explode(',','start_date,end_date');
$inputs[''.$Name[0]] = $Dates[0];
$Dates[0] = new Carbon($Dates[0]);
$Dates[1] = new Carbon($Dates[1]);
$inputs[''.$Name[0]] = $Dates[0]->format('Y-m-d');
$inputs[''.$Name[1]] = $Dates[1]->format('Y-m-d');
//dd($inputs);
}
foreach($request->files as $key_file => $value_file){
$nameArr = explode(',',$key_file);
$file = $value_file;
$destinationPath = 'public/uploads/customers';
\File::makeDirectory($destinationPath,0775,true,true);
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$encrypted_name = md5(uniqid().time()).".".$extension;
$file->move($destinationPath,$encrypted_name);
$inputs[''.$nameArr[0]] = $name;
$inputs[''.$nameArr[1]] = $encrypted_name;
}
Customer::create($inputs);
return redirect()->route('customers.index')->with('success',"Customer Saved successfully");
}
else{
$customers = Customer::where(['id'=>$request->input('id')])->first();
$inputs = $request->except('_token');
if($request->has('secret_key')){
$secret_key = bcrypt($request->secret_key);
$inputs['secret_key'] = $secret_key;
}
if($request->has('preference')){
$preference = implode(',',$request->preference);
$inputs['preference'] = $preference;
}
if($request->has('ready')){
$ready = implode(',',$request->ready);
$inputs['ready'] = $ready;
}
if($request->has('start_date,end_date')){
$Dates = explode('-',$request->input('start_date,end_date'));
$Name = explode(',','start_date,end_date');
$inputs[''.$Name[0]] = $Dates[0];
$Dates[0] = new Carbon($Dates[0]);
$Dates[1] = new Carbon($Dates[1]);
$inputs[''.$Name[0]] = $Dates[0]->format('Y-m-d');
$inputs[''.$Name[1]] = $Dates[1]->format('Y-m-d');
//dd($inputs);
}
foreach($request->files as $key_file => $value_file){
$destinationPath = 'public/uploads/customers';
\File::makeDirectory($destinationPath,0775,true,true);
$nameArr = explode(',',$key_file);
$OldFile = $customers->$nameArr[1];
if($OldFile!=''){
$OldFile = $destinationPath.'/'.$OldFile;
if(\File::exists($OldFile)){
\File::delete($OldFile);
}
}
$file = $value_file;
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$encrypted_name = md5(uniqid().time()).".".$extension;
$file->move($destinationPath,$encrypted_name);
$inputs[''.$nameArr[0]] = $name;
$inputs[''.$nameArr[1]] = $encrypted_name;
$SavedFile = $destinationPath.$encrypted_name;
}
$customers->update($inputs);
return redirect()->route('customers.index')->with('success',"Customer Saved successfully");
}
}
public function listCustomer(Request $request)
{
$customers = Customer::all();
$datatables = Datatables::of($customers)
->addColumn('actions', function($customers){
$html = '';
$html .= '<i class="fa fa-edit"></i>';
$html .= '<i class="fa fa-trash"></i>';
return $html;
})
->setRowId('id');
return $datatables->make();
}
public function destroy($id)
{
$customer = Customer::find($id);
$customer->delete();
return response()->json(array(
"status" => "success",
"message" => "Customer Deleted Successfully",
));
}
}
Maybe you could call a php beautifier on the file you created ? http://pear.php.net/package/PHP_Beautifier/
Note : you can call a command with exec
exec("php_beautifier $filename $filename");
It is hard to tell without more of your source but I imagine expressions like explode(',', $value["dbfield"] )[0] are catching some sort of tab character or importing blank fields that are somehow translated into spaces or tabs and causing the unwanted spacing.
#foreach($fields as $key => $value)
#if($value['dbfield'] == '')
#continue
#endif
#if($value['validation'])
#if(in_array('unique',explode(',',$value['validation'])))
'{{$value['dbfield']}}' => ${{$value['dbfield']}}_rules,
#else
#if(strpos($value["dbfield"],","))
'{{ explode(',', $value["dbfield"] )[0] }}' => '{{str_replace(',', '|', $value['validation'])}}',
#else
'{{$value['dbfield']}}' => '{{str_replace(',', '|', $value['validation'])}}',
#endif
#endif
#endif
#endforeach

Creating default object from empty value ( stdClass? )

The script run good, but only when I fetching out the groups of the user, it's says:
SteamUser.php (132): Creating default object from empty value
function getProfileData() {
//Set Base URL for the query:
if(empty($this->vanityURL)) {
$base = "http://steamcommunity.com/profiles/{$this->userID}/?xml=1";
} else {
$base = "http://steamcommunity.com/id/{$this->vanityURL}/?xml=1";
}
try {
$content = SteamUtility::fetchURL($base);
if ($content) {
$parsedData = new SimpleXMLElement($content);
} else {
return null;
}
} catch (Exception $e) {
//echo "Whoops! Something went wrong!\n\nException Info:\n" . $e . "\n\n";
return null;
}
if(!empty($parsedData)) {
$this->steamID64 = (string)$parsedData->steamID64;
$this->steamID = (string)$parsedData->steamID;
$this->stateMessage = (string)$parsedData->stateMessage;
$this->visibilityState = (int)$parsedData->visibilityState;
$this->privacyState = (string)$parsedData->privacyState;
$this->avatarIcon = (string)$parsedData->avatarIcon;
$this->avatarMedium = (string)$parsedData->avatarMedium;
$this->avatarFull = (string)$parsedData->avatarFull;
$this->vacBanned = (int)$parsedData->vacBanned;
$this->tradeBanState = (string)$parsedData->tradeBanState;
$this->isLimitedAccount = (string)$parsedData->isLimitedAccount;
$this->onlineState = (string)$parsedData->onlineState;
$this->inGameServerIP = (string)$parsedData->inGameServerIP;
//If their account is public, get that info:
if($this->privacyState == "public") {
$this->customURL = (string)$parsedData->customURL;
$this->memberSince = (string)$parsedData->memberSince;
$this->steamRating = (float)$parsedData->steamRating;
$this->hoursPlayed2Wk = (float)$parsedData->hoursPlayed2Wk;
$this->headline = (string)$parsedData->headline;
$this->location = (string)$parsedData->location;
$this->realname = (string)$parsedData->realname;
$this->summary = (string)$parsedData->summary;
}
//If they're in a game, grab that info:
if($this->onlineState == "in-game") {
$this->inGameInfo = array();
$this->inGameInfo["gameName"] = (string)$parsedData->inGameInfo->gameName;
$this->inGameInfo["gameLink"] = (string)$parsedData->inGameInfo->gameLink;
$this->inGameInfo["gameIcon"] = (string)$parsedData->inGameInfo->gameIcon;
$this->inGameInfo["gameLogo"] = (string)$parsedData->inGameInfo->gameLogo;
$this->inGameInfo["gameLogoSmall"] = (string)$parsedData->inGameInfo->gameLogoSmall;
}
//Any weblinks listed in their profile:
if(!empty($parsedData->weblinks)) {
$this->weblinks = array();
$i = 0;
foreach ($parsedData->weblinks->weblink as $weblink) {
$this->weblinks[$i]->title = (string)$weblink->title;
$this->weblinks[$i]->link = (string)$weblink->link;
$i++;
}
}
if(!empty($parsedData->groups)) {
$this->groups = array();
$i = 0;
foreach ($parsedData->groups->group as $group) {
$this->groups[$i]->groupID64 = (string)$group->groupID64; // row 132 in script
$this->groups[$i]->groupName = (string)$group->groupName;
$this->groups[$i]->groupURL = (string)$group->groupURL;
$this->groups[$i]->headline = (string)$group->headline;
$this->groups[$i]->summary = (string)$group->summary;
$this->groups[$i]->avatarIcon = (string)$group->avatarIcon;
$this->groups[$i]->avatarMedium = (string)$group->avatarMedium;
$this->groups[$i]->avatarFull = (string)$group->avatarFull;
$this->groups[$i]->memberCount = (string)$group->memberCount;
$this->groups[$i]->membersInChat = (string)$group->membersInChat;
$this->groups[$i]->membersInGame = (string)$group->membersInGame;
$this->groups[$i]->membersOnline = (string)$group->membersOnline;
$i++;
}
}
}
}
.
.
.
I already tried to using associative arrays, but didn't work; maybe with doing it all new. -_-
So, I can't set error_reporting(0) or ini_set at all.
I also used new stdClass() as a try. But I didn't get this running too.
You create an array.
$this->groups = array();
But in this array you donot create any object. You just use this array's elements (thoes are not initialized) as objects. You should add this line before your 132. row.
$this->groups[$i] = new Group();
Or something similar.
If you do not have Group class you should try
$this->groups[$i] = new stdClass();

I can not resolve this error in SugarCRM

In SugarCRM (program management) module called "projects" by default does not come with the "import", it added eh following programming steps:
http://forums.sugarcrm.com/f148/how-add-importación-opción-custom-modules-45612/
Now I throw the error when I Import Next:
Fatal error: Llamada a una función miembro get_importable_fields () en un no-objeto en C: \ Archivos de programa \ Apache Software Foundation \ Apache2.2 \ htdocs \ Azúcar \ modules \ Import \ v iews \ view.step3.php en línea 217
Please somebody help me ... if necessary ... I will upload the file so they can help view.step3.php
Here is the line 217:
$fields = $this->bean->get_importable_fields();
$options = array();
$defaultField = '';
global $current_language;
$moduleStrings = return_module_language($current_language, $this->bean->module_dir);
Here I publish the above lines:
class ImportViewStep3 extends ImportView
{
protected $pageTitleKey = 'LBL_STEP_3_TITLE';
protected $currentFormID = 'importstep3';
protected $previousAction = 'Confirm';
protected $nextAction = 'dupcheck';
/**
* #see SugarView::display()
*/
public function display()
{
global $mod_strings, $app_strings, $current_user, $sugar_config, $app_list_strings, $locale;
$this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
$has_header = ( isset( $_REQUEST['has_header']) ? 1 : 0 );
$sugar_config['import_max_records_per_file'] = ( empty($sugar_config['import_max_records_per_file']) ? 1000 : $sugar_config['import_max_records_per_file'] );
$this->ss->assign("CURRENT_STEP", $this->currentStep);
// attempt to lookup a preexisting field map
// use the custom one if specfied to do so in step 1
$mapping_file = new ImportMap();
$field_map = $mapping_file->set_get_import_wizard_fields();
$default_values = array();
$ignored_fields = array();
if ( !empty( $_REQUEST['source_id']))
{
$GLOBALS['log']->fatal("Loading import map properties.");
$mapping_file = new ImportMap();
$mapping_file->retrieve( $_REQUEST['source_id'],false);
$_REQUEST['source'] = $mapping_file->source;
$has_header = $mapping_file->has_header;
if (isset($mapping_file->delimiter))
$_REQUEST['custom_delimiter'] = $mapping_file->delimiter;
if (isset($mapping_file->enclosure))
$_REQUEST['custom_enclosure'] = htmlentities($mapping_file->enclosure);
$field_map = $mapping_file->getMapping();
//print_r($field_map);die();
$default_values = $mapping_file->getDefaultValues();
$this->ss->assign("MAPNAME",$mapping_file->name);
$this->ss->assign("CHECKMAP",'checked="checked" value="on"');
}
else
{
$classname = $this->getMappingClassName(ucfirst($_REQUEST['source']));
//Set the $_REQUEST['source'] to be 'other' for ImportMapOther special case
if($classname == 'ImportMapOther')
{
$_REQUEST['source'] = 'other';
}
if (class_exists($classname))
{
$mapping_file = new $classname;
$ignored_fields = $mapping_file->getIgnoredFields($_REQUEST['import_module']);
$field_map2 = $mapping_file->getMapping($_REQUEST['import_module']);
$field_map = array_merge($field_map,$field_map2);
}
}
$delimiter = $this->getRequestDelimiter();
$this->ss->assign("CUSTOM_DELIMITER", $delimiter);
$this->ss->assign("CUSTOM_ENCLOSURE", ( !empty($_REQUEST['custom_enclosure']) ? $_REQUEST['custom_enclosure'] : "" ));
//populate import locale values from import mapping if available, these values will be used througout the rest of the code path
$uploadFileName = $_REQUEST['file_name'];
// Now parse the file and look for errors
$importFile = new ImportFile( $uploadFileName, $delimiter, html_entity_decode($_REQUEST['custom_enclosure'],ENT_QUOTES), FALSE);
if ( !$importFile->fileExists() ) {
$this->_showImportError($mod_strings['LBL_CANNOT_OPEN'],$_REQUEST['import_module'],'Step2');
return;
}
$charset = $importFile->autoDetectCharacterSet();
// retrieve first 3 rows
$rows = array();
//Keep track of the largest row count found.
$maxFieldCount = 0;
for ( $i = 0; $i < 3; $i++ )
{
$rows[] = $importFile->getNextRow();
$maxFieldCount = $importFile->getFieldCount() > $maxFieldCount ? $importFile->getFieldCount() : $maxFieldCount;
}
$ret_field_count = $maxFieldCount;
// Bug 14689 - Parse the first data row to make sure it has non-empty data in it
$isempty = true;
if ( $rows[(int)$has_header] != false ) {
foreach ( $rows[(int)$has_header] as $value ) {
if ( strlen(trim($value)) > 0 ) {
$isempty = false;
break;
}
}
}
if ($isempty || $rows[(int)$has_header] == false) {
$this->_showImportError($mod_strings['LBL_NO_LINES'],$_REQUEST['import_module'],'Step2');
return;
}
// save first row to send to step 4
$this->ss->assign("FIRSTROW", base64_encode(serialize($rows[0])));
// Now build template
$this->ss->assign("TMP_FILE", $uploadFileName );
$this->ss->assign("SOURCE", $_REQUEST['source'] );
$this->ss->assign("TYPE", $_REQUEST['type'] );
$this->ss->assign("DELETE_INLINE_PNG", SugarThemeRegistry::current()->getImage('basic_search','align="absmiddle" alt="'.$app_strings['LNK_DELETE'].'" border="0"'));
$this->ss->assign("PUBLISH_INLINE_PNG", SugarThemeRegistry::current()->getImage('advanced_search','align="absmiddle" alt="'.$mod_strings['LBL_PUBLISH'].'" border="0"'));
$this->instruction = 'LBL_SELECT_MAPPING_INSTRUCTION';
$this->ss->assign('INSTRUCTION', $this->getInstruction());
$this->ss->assign("MODULE_TITLE", $this->getModuleTitle(false));
$this->ss->assign("STEP4_TITLE",
strip_tags(str_replace("\n","",getClassicModuleTitle(
$mod_strings['LBL_MODULE_NAME'],
array($mod_strings['LBL_MODULE_NAME'],$mod_strings['LBL_STEP_4_TITLE']),
false
)))
);
$this->ss->assign("HEADER", $app_strings['LBL_IMPORT']." ". $mod_strings['LBL_MODULE_NAME']);
// we export it as email_address, but import as email1
$field_map['email_address'] = 'email1';
// build each row; row count is determined by the the number of fields in the import file
$columns = array();
$mappedFields = array();
// this should be populated if the request comes from a 'Back' button click
$importColumns = $this->getImportColumns();
$column_sel_from_req = false;
if (!empty($importColumns)) {
$column_sel_from_req = true;
}
for($field_count = 0; $field_count < $ret_field_count; $field_count++) {
// See if we have any field map matches
$defaultValue = "";
// Bug 31260 - If the data rows have more columns than the header row, then just add a new header column
if ( !isset($rows[0][$field_count]) )
$rows[0][$field_count] = '';
// See if we can match the import row to a field in the list of fields to import
$firstrow_name = trim(str_replace(":","",$rows[0][$field_count]));
if ($has_header && isset( $field_map[$firstrow_name] ) ) {
$defaultValue = $field_map[$firstrow_name];
}
elseif (isset($field_map[$field_count])) {
$defaultValue = $field_map[$field_count];
}
elseif (empty( $_REQUEST['source_id'])) {
$defaultValue = trim($rows[0][$field_count]);
}
// build string of options
$fields = $this->bean->get_importable_fields();
this is my coding project.php:
class Project extends SugarBean {
// database table columns
var $id;
var $date_entered;
var $date_modified;
var $assigned_user_id;
var $modified_user_id;
var $created_by;
var $name;
var $description;
var $deleted;
// related information
var $assigned_user_name;
var $modified_by_name;
var $created_by_name;
var $account_id;
var $contact_id;
var $opportunity_id;
var $email_id;
var $estimated_start_date;
// calculated information
var $total_estimated_effort;
var $total_actual_effort;
var $object_name = 'Project';
var $module_dir = 'Project';
var $new_schema = true;
var $table_name = 'project';
var $importable = true;
// This is used to retrieve related fields from form posts.
var $additional_column_fields = array(
'account_id',
'contact_id',
'opportunity_id',
);
var $relationship_fields = array(
'account_id' => 'accounts',
'contact_id'=>'contacts',
'opportunity_id'=>'opportunities',
'email_id' => 'emails',
);
//////////////////////////////////////////////////////////////////
// METHODS
//////////////////////////////////////////////////////////////////
/**
*
*/
function Project()
{
parent::SugarBean();
}
/**
* overriding the base class function to do a join with users table
*/
/**
*
*/
function fill_in_additional_detail_fields()
{
parent::fill_in_additional_detail_fields();
$this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
//$this->total_estimated_effort = $this->_get_total_estimated_effort($this->id);
//$this->total_actual_effort = $this->_get_total_actual_effort($this->id);
}
/**
*
*/
function fill_in_additional_list_fields()
{
parent::fill_in_additional_list_fields();
$this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
//$this->total_estimated_effort = $this->_get_total_estimated_effort($this->id);
//$this->total_actual_effort = $this->_get_total_actual_effort($this->id);
}
/**
* Save changes that have been made to a relationship.
*
* #param $is_update true if this save is an update.
*/
function save_relationship_changes($is_update, $exclude=array())
{
parent::save_relationship_changes($is_update, $exclude);
$new_rel_id = false;
$new_rel_link = false;
//this allows us to dynamically relate modules without adding it to the relationship_fields array
if(!empty($_REQUEST['relate_id']) && !in_array($_REQUEST['relate_to'], $exclude) && $_REQUEST['relate_id'] != $this->id){
$new_rel_id = $_REQUEST['relate_id'];
$new_rel_relname = $_REQUEST['relate_to'];
if(!empty($this->in_workflow) && !empty($this->not_use_rel_in_req)) {
$new_rel_id = $this->new_rel_id;
$new_rel_relname = $this->new_rel_relname;
}
$new_rel_link = $new_rel_relname;
//Try to find the link in this bean based on the relationship
foreach ( $this->field_defs as $key => $def ) {
if (isset($def['type']) && $def['type'] == 'link'
&& isset($def['relationship']) && $def['relationship'] == $new_rel_relname) {
$new_rel_link = $key;
}
}
if ($new_rel_link == 'contacts') {
$accountId = $this->db->getOne('SELECT account_id FROM accounts_contacts WHERE contact_id=' . $this->db->quoted($new_rel_id));
if ($accountId !== false) {
if($this->load_relationship('accounts')){
$this->accounts->add($accountId);
}
}
}
}
}
/**
*
*/
function _get_total_estimated_effort($project_id)
{
$return_value = '';
$query = 'SELECT SUM('.$this->db->convert('estimated_effort', "IFNULL", 0).') total_estimated_effort';
$query.= ' FROM project_task';
$query.= " WHERE parent_id='{$project_id}' AND deleted=0";
$result = $this->db->query($query,true," Error filling in additional detail fields: ");
$row = $this->db->fetchByAssoc($result);
if($row != null)
{
$return_value = $row['total_estimated_effort'];
}
return $return_value;
}
/**
*
*/
function _get_total_actual_effort($project_id)
{
$return_value = '';
$query = 'SELECT SUM('.$this->db->convert('actual_effort', "IFNULL", 0).') total_actual_effort';
$query.= ' FROM project_task';
$query.= " WHERE parent_id='{$project_id}' AND deleted=0";
$result = $this->db->query($query,true," Error filling in additional detail fields: ");
$row = $this->db->fetchByAssoc($result);
if($row != null)
{
$return_value = $row['total_actual_effort'];
}
return $return_value;
}
/**
*
*/
function get_summary_text()
{
return $this->name;
}
/**
*
*/
function build_generic_where_clause ($the_query_string)
{
$where_clauses = array();
$the_query_string = $GLOBALS['db']->quote($the_query_string);
array_push($where_clauses, "project.name LIKE '%$the_query_string%'");
$the_where = '';
foreach($where_clauses as $clause)
{
if($the_where != '') $the_where .= " OR ";
$the_where .= $clause;
}
return $the_where;
}
function get_list_view_data()
{
$field_list = $this->get_list_view_array();
$field_list['USER_NAME'] = empty($this->user_name) ? '' : $this->user_name;
$field_list['ASSIGNED_USER_NAME'] = $this->assigned_user_name;
return $field_list;
}
function bean_implements($interface){
switch($interface){
case 'ACL':return true;
}
return false;
}
function create_export_query(&$order_by, &$where, $relate_link_join='')
{
$custom_join = $this->custom_fields->getJOIN(true, true,$where);
if($custom_join)
$custom_join['join'] .= $relate_link_join;
$query = "SELECT
project.*,
users.user_name as assigned_user_name ";
if($custom_join){
$query .= $custom_join['select'];
}
$query .= " FROM project ";
if($custom_join){
$query .= $custom_join['join'];
}
$query .= " LEFT JOIN users
ON project.assigned_user_id=users.id ";
$where_auto = " project.deleted=0 ";
if($where != "")
$query .= "where ($where) AND ".$where_auto;
else
$query .= "where ".$where_auto;
if(!empty($order_by)){
//check to see if order by variable already has table name by looking for dot "."
$table_defined_already = strpos($order_by, ".");
if($table_defined_already === false){
//table not defined yet, define accounts to avoid "ambigous column" SQL error
$query .= " ORDER BY $order_by";
}else{
//table already defined, just add it to end of query
$query .= " ORDER BY $order_by";
}
}
return $query;
}
function getAllProjectTasks(){
$projectTasks = array();
$query = "SELECT * FROM project_task WHERE project_id = '" . $this->id. "' AND deleted = 0 ORDER BY project_task_id";
$result = $this->db->query($query,true,"Error retrieving project tasks");
$row = $this->db->fetchByAssoc($result);
while ($row != null){
$projectTaskBean = new ProjectTask();
$projectTaskBean->id = $row['id'];
$projectTaskBean->retrieve();
array_push($projectTasks, $projectTaskBean);
$row = $this->db->fetchByAssoc($result);
}
return $projectTasks;
}
}
?>

Suggested image rotator for use in Yii Framework App?

I have an extension that displays a basic user profile derived from the Yii widget class. My extension is defined as follows:
class BasicProfile extends CWidget
{
public $user_id;
private $userinfo = array();
private $userdetail = array();
private $availibility = array();
private $availabletime = array();
private $usereducation = array();
private $userlanguages = array();
private $userlivingplace = array();
public function init()
{
$this->userinfo = $users = Users::model()->findByPk($this->user_id);
$this->userdetail = $users->profile;
$this->availibility = $users->user_availibility;
$this->availabletime = $users->user_availabletime;
$this->usereducation = $users->user_education;
$this->userlanguages = $users->user_languagues;
$this->userlivingplace = $users->user_livingplaces;
}
public function run() {
$this->getUserDetail();
}
public function getUserDetail(){
$basic = $this->userinfo;
$detail = $this->userdetail;
$availibility = $this->availibility;
$availabletime = $this->availabletime;
$usereducation = $this->usereducation;
$userlanguages = $this->userlanguages;
$userlivingplaces = $this->userlivingplace;
$age = getAge(strtotime($detail['date_of_birth']));
$is_smoker = isSmoker($detail['is_smoker']);
$education = '';
foreach ($usereducation as $ue)
{
$e = $ue->educ;
$education .= $e['edu_name']. ', ';
}
$education = substr($education, 0, -2);
$languages = '';
foreach ($userlanguages as $ul)
{
$l = $ul->lang;
$languages .= $l['language_title']. ', ';
}
$languages = substr($languages, 0, -2);
$condition = array('where_condition'=>'up.user_id=:id AND up.is_currently_own=:own', 'where_data'=>array(':id'=>(int)$this->user_id, ':own'=>'Yes'));
$user_pets = Users::model()->getUserPets($condition);
$profile_images = UserProfileImages::model()->getProfileImages( array('select'=>'all'), $this->user_id );
foreach( $profile_images as $profile_img ) {
$images[] = $profile_img->profile_image;
}
$image = '';
if( $images ){
$main_image = HTTP_HOST . PROFILE_IMAGES_THUMB . $images[0];
$image = '<img src="'. $main_image .'" />';
}
$address1 = $basic['address1'];
if($basic['address2'] != "")
$address1 .= ", ".$basic['address2'];
$address2 = $basic['city']." ".$basic['state'].", ". $basic['zip'];
$editprofile = url('/users/account');
$editimglink = url('/images/icons/Modify.png');
}
}
My goal is to simply call this extension in my view as follwos:
$this->widget('ext.UserProfile.BasicProfile',array('user_id'=>$user_id));
However, I'm wondering if my extension is the proper place to encapsulate the image rotator? Should the rotator be included in the extension, or as part of the view? Should a generic JQuery image rotator be used, or is there one that plays well with Yii Framework?
I like to use JQuery.Cycle as my image rotator. I suggest that you build an extension with assets to keep the code in one place. you can however put your css in your theme folder and build a basic css in your extension to keep it clean like the basic pager of yii.
You could call your widget like this:
$this->widget("application.extensions.rotator", array("images" => array("/path/to/image/1", "/path/to/image/2"), "prevBtn" => "/path/to/prev/button");

Categories