error reading db in joomla - joomla

While i run a component i am getting 500 - An error has occurred error reading db in joomla.
My configuration file is perfect.
I don't know what else to change..
Any guidance will be helpful
Thanks in advance...
//No direct acesss
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class DealsModelDeals extends JModel {
function getDeals(){
$db = $this->getDBO();
$db->setQuery('SELECT * from #__todaysdeal');
$deals = $db->loadObjectList();
if ($deals === null)
JError::raiseError(500, 'Error reading db');
return $deals;
}
function getDeal($id){
$query = ' SELECT * FROM #__todaysdeal '. ' WHERE id = '.$id;
$db = $this->getDBO();
$db->setQuery($query);
$deal = $db->loadObject();
if ($deal === null)
JError::raiseError(500, 'Deal with ID: '.$id.' not found.');
else
return $deal;
}
/**
* Method that returns an empty greeting with id 0
*
* #access public
*/
function getNewDeal(){
$dealTableRow =& $this->getTable('deals');
$dealTableRow->id=0;
$dealTableRow->clientName='';
return $dealTableRow;
}
/**
* Method to store a greeting in the DB
*
* #access public
*/
function saveDeal($deal)
{
//Parameter not necessary because our model is named DealsModelDeals (used to ilustrate that you can specify an alternative name to the JTable extending class)
$dealTableRow =& $this->getTable('deals');
//print_r($dealTableRow);
//print_r($_FILES); exit;
// Bind the form fields to the todaysdeal table
if (!$dealTableRow->bind($deal)) {
JError::raiseError(500, 'Error binding data');
}
// Make sure the deal record is valid
if (!$dealTableRow->check()) {
JError::raiseError(500, 'Invalid data');
}
// Insert/update this record in the db
if (!$dealTableRow->store()) {
$errorMessage = $dealTableRow->getError();
JError::raiseError(500, 'Error binding data: '.$errorMessage);
}
$id = $dealTableRow->id;
if(!empty($_FILES['dealImage']))
{
$file = $_FILES['dealImage'];
$id = $dealTableRow->id;
if ((($_FILES["dealImage"]["type"] == "image/gif") || ($_FILES["dealImage"]["type"] == "image/jpeg") || ($_FILES["dealImage"]["type"] == "image/pjpeg")) && ($_FILES["dealImage"]["size"] < 150000))
{
if ($_FILES["dealImage"]["error"] > 0)
{
echo "Return Code: " . $_FILES["dealImage"]["error"] . "<br />";
}
else
{
if (file_exists("components/com_deals/dealImages/" . $_FILES["dealImage"]["name"])) {
$_FILES["dealImage"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["dealImage"]["tmp_name"], "components/com_deals/dealImages/" .$id."_".$_FILES["dealImage"]["name"]);
echo "Stored in: " . "dealImages/" . $_FILES["dealImage"]["name"];
}
}
}
else
{
}
}
$dealImage = $_FILES['dealImage']['name'];
$dealImage .= (!empty($_FILES['dealImage']['name'])) ? ' ' . $_FILES['dealImage']['name'] : '';
$query = "UPDATE #__todaysdeal SET dealImage='".$id."_".$_FILES['dealImage']['name']."' WHERE id='".$id."'";
$db = $this->getDBO();
$db->setQuery($query);
$db->query();
//If we get here and with no raiseErrors, then everythign went well
}
function deleteDeals($arrayIDs)
{
$query = "DELETE FROM #__todaysdeal WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error deleting Deals: '.$errorMessage);
}
}
function dealsUploadPhoto($file, $id)
{
//UPLOAD FILE
$config = & JComponentHelper::getParams('com_deals');
$allowed = array('image/pjpeg', 'image/jpeg', 'image/jpg', 'image/png', 'image/x-png', 'image/gif', 'image/ico', 'image/x-icon');
$pwidth = $config->get('pwidth');
$pheight = $config->get('pheight');
$maxsize = $config->get('maxsize');
if($file['size'] > 0 && ($file['size'] / 1024 < $maxsize)){
if(!file_exists(JPATH_SITE . DS. 'images' . DS . 'deals'))
{
if(mkdir(JPATH_SITE . DS . 'images' . DS . 'deals')) {
JPath::setPermissions(JPATH_SITE . DS . 'images' . DS . 'deals', '0777');
if(file_exists(JPATH_SITE . DS . 'images' . DS . 'index.html')) {
copy(JPATH_SITE . DS . 'images' . DS . 'index.html', JPATH_SITE . DS . 'images' . DS . 'deals/index.html');
}
}
}
if($file['error'] != 0){
tpJobsMsgAlert('Upload file photo error.');
exit ();
}
if($file['size'] == 0){
$file = null;
}
if(!in_array($file['type'], $allowed)) {
$file = null;
}
if ($file != null){
$dest = JPATH_SITE.DS.'images'.DS.'deals'.DS.$id.'.jpg';
if(file_exists($dest))
{
$del = unlink($dest);
}
$soure = $file['tmp_name'];
jimport('joomla.filesystem.file');
$uploaded = JFile::upload($soure,$dest);
$fileAtr = getimagesize($dest);
$widthOri = $fileAtr[0];
$heightOri = $fileAtr[1];
$type = $fileAtr['mime'];
$img = false;
switch ($type)
{
case 'image/jpeg':
case 'image/jpg':
case 'image/pjpeg':
$img = imagecreatefromjpeg($dest);
break;
case 'image/ico':
$img = imagecreatefromico($dest);
break;
case 'image/x-png':
case 'image/png':
$img = imagecreatefrompng($dest);
break;
case 'image/gif':
$img = imagecreatefromgif($dest);
break;
}
if(!$img)
{
return false;
}
$curr = #getimagesize($dest);
$perc_w = $pwidth / $widthOri;
$perc_h = $pheight / $heightOri;
if(($widthOri<$pwidth) && ($heightOri<$height))
{
return;
}
if($perc_h > $perc_w)
{
$pwidth = $pwidth;
$pheight = round($heightOri * $perc_w);
}
else
{
$pheight = $pheight;
$pwidth = round($widthOri * $perc_h);
}
$nwimg = imagecreatetruecolor($pwidth, $pheight);
imagecopyresampled($nwimg, $img, 0, 0, 0, 0, $pwidth, $pheight, $widthOri, $heightOri);
imagejpeg($nwimg, $dest, 100);
imagedestroy($nwimg);
imagedestroy($img);
}
}else{
if($file['size'] / 1024 > $maxsize){
dealsMsgAlert('Size of file photo is too big. Maximum size".$maxsize." KB');
exit ();
}
}
}
function dealsMsgAlert($msg)
{
if (!headers_sent())
{
while(#ob_end_clean());
ob_start();
echo "<script> alert('".$msg."'); window.history.go(-1); </script>\n";
$out = ob_get_contents();
ob_end_clean();
echo $out;
exit();
}
echo "<script> alert('".$msg."'); window.history.go(-1); </script>\n";
exit();
}
}
?>

The problem that causes the red screen with 500 Error is happening because you are raising an exception if the requested quote is does not exist. You should not use JError::raiseError().
Use one of the following instead:
// This will set error to the model. You can get the errors from
// the model by your controller $model->getErrors() and output them to the screen.
$this->setError('ERROR MESSAGE GOES HERE');
OR
// This will output errors to the screen right the way
JFactory::getApplication()->enqueueMessage('ERROR MESSAGE GOES HERE', 'message');
Model already has _db property, you do not need to get db into variable. You can access it like this $this->_db. You can read about Joomla Model class here.
Also within your model you are using
$db = $this->getDBO();
$db->setQuery('SELECT * from #__todaysdeal');
$deals = $db->loadObjectList();
Model has simplified method to load list of object, like so
$deals =& $this->_getList('SELECT * from #__todaysdeal');

Related

multiple voyager browse blade laravel

i have Product Model and it have bread in voyager and everything is ok.
Products have publisher_id column if null == main else int(id of publisher).
i want create multiple browse blade but one of those is default voyager blade
and another where('publisher_id','!=',null)
to show .
how to created it with route ?
thanks .
fixed with resource route
Route::resource('products/index/publisher', VoyagerProductPublisherController::class);
Route::resource('products/index/notaccept', VoyagerProductPublisherNotAcceptController::class);
and then in controllers index function write query
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = \request()->segment(3);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$getter = 'paginate';
$search = (object)['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchNames = $dataType->browseRows->mapWithKeys(function ($row) {
return [$row['field'] => $row->getTranslatedAttribute('display_name')];
});
}
$orderBy = $request->get('order_by', $dataType->order_column);
$sortOrder = $request->get('sort_order', $dataType->order_direction);
$usesSoftDeletes = false;
$showSoftDeleted = false;
// Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
$query = $model::select($dataType->name . '.*');
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope' . ucfirst($dataType->scope))) {
$query->{$dataType->scope}();
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$usesSoftDeletes = true;
if ($request->showSoftDeleted && $request->showSoftDeleted == 1) {
$showSoftDeleted = true;
$query = $query->onlyTrashed();
}
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'browse');
if ($search->value != '' && $search->key && $search->filter) {
$search_filter = ($search->filter == 'equals') ? '=' : 'LIKE';
$search_value = ($search->filter == 'equals') ? $search->value : '%' . $search->value . '%';
$searchField = $dataType->name . '.' . $search->key;
if ($row = $this->findSearchableRelationshipRow($dataType->rows->where('type', 'relationship'), $search->key)) {
$query->whereIn(
$searchField,
$row->details->model::where($row->details->label, $search_filter, $search_value)->pluck('id')->toArray()
);
} else {
if ($dataType->browseRows->pluck('field')->contains($search->key)) {
$query->where($searchField, $search_filter, $search_value);
}
}
}
$row = $dataType->rows->where('field', $orderBy)->firstWhere('type', 'relationship');
if ($orderBy && (in_array($orderBy, $dataType->fields()) || !empty($row))) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
if (!empty($row)) {
$query->select([
$dataType->name . '.*',
'joined.' . $row->details->label . ' as ' . $orderBy,
])->leftJoin(
$row->details->table . ' as joined',
$dataType->name . '.' . $row->details->column,
'joined.' . $row->details->key,
);
}
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder)->where('publisher_id','!=',null),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT)->where('publisher_id','!=',null), 'paginate'], request()->perPage ?? 10);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC')->where('publisher_id','!=',null), $getter]);
}
// Replace relationships' keys for labels and create READ links if a slug is provided.
$dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType);
} else {
// If Model doesn't exist, get data from table name
$dataTypeContent = call_user_func([DB::table($dataType->name)->where('publisher_id','!=',null), $getter]);
$model = false;
}
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($model);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'browse', $isModelTranslatable);
// Check if server side pagination is enabled
$isServerSide = isset($dataType->server_side) && $dataType->server_side;
// Check if a default search key is set
$defaultSearchKey = $dataType->default_search_key ?? null;
// Actions
$actions = [];
if (!empty($dataTypeContent->first())) {
foreach (Voyager::actions() as $action) {
$action = new $action($dataType, $dataTypeContent->first());
if ($action->shouldActionDisplayOnDataType()) {
$actions[] = $action;
}
}
}
//Define showCheckboxColumn
$showCheckboxColumn = false;
if (Auth::guard('admin')->user()->can('delete', app($dataType->model_name))) {
$showCheckboxColumn = true;
} else {
foreach ($actions as $action) {
if (method_exists($action, 'massAction')) {
$showCheckboxColumn = true;
}
}
}
// Define orderColumn
$orderColumn = [];
if ($orderBy) {
$index = $dataType->browseRows->where('field', $orderBy)->keys()->first() + ($showCheckboxColumn ? 1 : 0);
$orderColumn = [[$index, $sortOrder ?? 'desc']];
}
// Define list of columns that can be sorted server side
$sortableColumns = $this->getSortableColumns($dataType->browseRows);
$view = 'voyager::bread.publisher';
if (view()->exists("voyager::$slug.publisher")) {
$view = "voyager::$slug.publisher";
}
return Voyager::view($view, compact(
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortableColumns',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
// in controller two
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = \request()->segment(3);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$getter = 'paginate';
$search = (object)['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchNames = $dataType->browseRows->mapWithKeys(function ($row) {
return [$row['field'] => $row->getTranslatedAttribute('display_name')];
});
}
$orderBy = $request->get('order_by', $dataType->order_column);
$sortOrder = $request->get('sort_order', $dataType->order_direction);
$usesSoftDeletes = false;
$showSoftDeleted = false;
// Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
$query = $model::select($dataType->name . '.*');
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope' . ucfirst($dataType->scope))) {
$query->{$dataType->scope}();
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$usesSoftDeletes = true;
if ($request->showSoftDeleted && $request->showSoftDeleted == 1) {
$showSoftDeleted = true;
$query = $query->onlyTrashed();
}
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'browse');
if ($search->value != '' && $search->key && $search->filter) {
$search_filter = ($search->filter == 'equals') ? '=' : 'LIKE';
$search_value = ($search->filter == 'equals') ? $search->value : '%' . $search->value . '%';
$searchField = $dataType->name . '.' . $search->key;
if ($row = $this->findSearchableRelationshipRow($dataType->rows->where('type', 'relationship'), $search->key)) {
$query->whereIn(
$searchField,
$row->details->model::where($row->details->label, $search_filter, $search_value)->pluck('id')->toArray()
);
} else {
if ($dataType->browseRows->pluck('field')->contains($search->key)) {
$query->where($searchField, $search_filter, $search_value);
}
}
}
$row = $dataType->rows->where('field', $orderBy)->firstWhere('type', 'relationship');
if ($orderBy && (in_array($orderBy, $dataType->fields()) || !empty($row))) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
if (!empty($row)) {
$query->select([
$dataType->name . '.*',
'joined.' . $row->details->label . ' as ' . $orderBy,
])->leftJoin(
$row->details->table . ' as joined',
$dataType->name . '.' . $row->details->column,
'joined.' . $row->details->key,
);
}
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder)->where('accept',0),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT)->where('accept',0), 'paginate'], request()->perPage ?? 10);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC')->where('accept',0), $getter]);
}
// Replace relationships' keys for labels and create READ links if a slug is provided.
$dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType);
} else {
// If Model doesn't exist, get data from table name
$dataTypeContent = call_user_func([DB::table($dataType->name)->where('accept',0), $getter]);
$model = false;
}
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($model);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'browse', $isModelTranslatable);
// Check if server side pagination is enabled
$isServerSide = isset($dataType->server_side) && $dataType->server_side;
// Check if a default search key is set
$defaultSearchKey = $dataType->default_search_key ?? null;
// Actions
$actions = [];
if (!empty($dataTypeContent->first())) {
foreach (Voyager::actions() as $action) {
$action = new $action($dataType, $dataTypeContent->first());
if ($action->shouldActionDisplayOnDataType()) {
$actions[] = $action;
}
}
}
//Define showCheckboxColumn
$showCheckboxColumn = false;
if (Auth::guard('admin')->user()->can('delete', app($dataType->model_name))) {
$showCheckboxColumn = true;
} else {
foreach ($actions as $action) {
if (method_exists($action, 'massAction')) {
$showCheckboxColumn = true;
}
}
}
// Define orderColumn
$orderColumn = [];
if ($orderBy) {
$index = $dataType->browseRows->where('field', $orderBy)->keys()->first() + ($showCheckboxColumn ? 1 : 0);
$orderColumn = [[$index, $sortOrder ?? 'desc']];
}
// Define list of columns that can be sorted server side
$sortableColumns = $this->getSortableColumns($dataType->browseRows);
$view = 'voyager::bread.notaccept';
if (view()->exists("voyager::$slug.notaccept")) {
$view = "voyager::$slug.notaccept";
}
return Voyager::view($view, compact(
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortableColumns',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
thanks for view .

DataBase Schema File (.sql file ) Download with laravel

Schenario :
1) suppose that i have a database called myDataBase
2) Assume that myDataBase have some tables like A,B,C,D
3) i have to download the schema of the table A,B from the database with name myDataBase
Hope you have done the migration of all the table of your project . If you are using a xampp server then goto http://localhost/phpmyadmin and select your database and then goto export tab on the top tab bar and simply export with go button
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "root";
$mysqlPassword = "";
$mysqlHostName = "localhost";
$DbName = "ukkoteknik";
$backup_name = "mybackup.sql";
$tables = array("admin", "sample");
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables, $backup_name=false );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$date = date("Y-m-d");
$backup_name = $backup_name ? $backup_name : $name.".$date.sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
//echo $content; exit;
}
?>

Assign custom image to programmatically created product

once guest user click on button "add to cart1", we are doing below things:
we are creating simple product programmatically
we are assigning custom image to that product.
Display one more pop up to Login to site by click on "login" button
once user click on "login button, we are doing below things:
we are creating simple product programmatically
we are not assigning custom image to that product.
but here we need to assign custom image to that product.
public function thisSimpleProductAndRedirectAction()
{
$originalProductId = $this->getRequest()->getParam("id");
// $productNameArray = explode(" - ",$this->getRequest()->getParam("id"));
// $originalProductId = $productNameArray[0];
$newImagePath = $this->getRequest()->getParam("image");
$originalProduct = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($originalProductId);
if ($product = $this->_createProduct(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE, true, $originalProduct, $newImagePath)) {
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode("custom image saving"));
}
else{
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode("custom image not saving"));
}
}
protected function _thisImage($type, $doSave = true, $originalProduct, $newImagePath = "")
{
// code for Guest
Mage::register('isSecureArea',true);
$session = Mage::getSingleton('customer/session');
$result = array(
'success' => false
);
$login ="";
$productId ="";
if ($this->getRequest()->isPost()) {
$login = $this->getRequest()->getPost('login');
$productId = $this->getRequest()->getPost('product_id');
}
// echo $login['product_id'];die;
// if (!empty($login['username']) && !empty($login['password'])) {
try {
if(isset($login) && (is_array($login) && !empty($login)) || ($login!="")){
$session->login($login['username'], $login['password']);
$result['redirect'] = $this->_getRefererUrl() ? $this->_getRefererUrl() : Mage::getUrl('customer/account', array(
'_secure' => true
));
$result['success'] = true;
$customerId = Mage::getSingleton('customer/session')->getCustomerId();
}
else{
$customerId = "";
}
// code for guest end
$product->setName($originalProduct->getName());
// add images
$images = array(
'thumbnail' => 'image.png', // displaying under cart page
'image' => 'image.png' // displaying under my design
);
foreach ($images as $imageType => $imageFileName) {
if ($newImagePath != "") {
$dir = Mage::getBaseDir('media') . DS . 'custom_product_preview/quote/';
$path = $dir . $newImagePath;
} else {
$dir = Mage::getBaseDir('media') . DS . 'example/amasty/';
$path = $dir . $imageFileName;
}
//echo $path."<br>";
if (file_exists($path)) {
try {
$product->addImageToMediaGallery($path, $imageType, false);
}
catch (Exception $e) {
echo $e->getMessage();
}
} else {
echo "Can not find image by path: `{$path}`<br/>";
}
}
$emailimage = Mage::helper('catalog/image')->init($product, 'thumbnail');
if ($doSave)
$product->save();
return $product;
// code for guest
}
catch (Mage_Core_Exception $e) {
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
$message = Mage::helper('customer')->__('This account is not confirmed. Click here to resend confirmation email.', Mage::helper('customer')->getEmailConfirmationUrl($login['username']));
break;
case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
$message = $e->getMessage();
break;
default:
$message = $e->getMessage();
}
$result['error'] = $message;
$session->setUsername($login['username']);
}
catch (Exception $e) {
$result = "ERROR :".$e->getMesage();
Mage::unregister('isSecureArea');
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
// code for guest end
}
You need to replace your code :
if ($newImagePath != "")
{
$dir = Mage::getBaseDir('media') . DS . 'custom_product_preview/quote/';
$path = $dir . $newImagePath;
}
else
{
$dir = Mage::getBaseDir('media') . DS . 'example/amasty/';
$path = $dir . $imageFileName;
}
with this code :
$path = '';
if ($newImagePath != "")
{
$dir = Mage::getBaseDir('media') . DS . 'custom_product_preview/quote/';
$path = $dir . $newImagePath;
}
else
{
$dir = Mage::getBaseDir('media') . DS . 'example/amasty/';
$path = $dir . $imageFileName;
}

Get the information you entered to ID

This file is the database ID information all the fields and went and came to a Blade, I want to an ID information entered in the same panel Blade I send my face.
class DataGrid extends DataSet
{
protected $fields = array();
/** #var Column[] */
public $columns = array();
public $headers = array();
public $rows = array();
public $output = "";
public $attributes = array("class" => "table");
public $checkbox_form = false;
protected $row_callable = array();
/**
* #param string $name
* #param string $label
* #param bool $orderby
*
* #return Column
*/
public function add($name, $label = null, $orderby = false)
{
$column = new Column($name, $label, $orderby);
$this->columns[$column->name] = $column;
if (!in_array($name,array("_edit"))) {
$this->headers[] = $label;
}
if ($orderby) {
$this->addOrderBy($column->orderby_field);
}
return $column;
}
//todo: like "field" for DataForm, should be nice to work with "cell" as instance and "row" as collection of cells
public function build($view = '')
{
($view == '') and $view = 'rapyd::datagrid';
parent::build();
Persistence::save();
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
$cell = new Cell($column->name);
$sanitize = (count($column->filters) || $column->cell_callable) ? false : true;
$value = $this->getCellValue($column, $tablerow, $sanitize);
$cell->value($value);
$cell->parseFilters($column->filters);
if ($column->cell_callable) {
$callable = $column->cell_callable;
$cell->value($callable($cell->value, $tablerow));
}
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
$this->rows[] = $row;
}
$routeParamters = \Route::current()->parameters();
return \View::make($view, array('dg' => $this, 'buttons'=>$this->button_container, 'label'=>$this->label,
'current_entity' => $routeParamters['entity']));
}
public function buildCSV($file = '', $timestamp = '', $sanitize = true,$del = array())
{
$this->limit = null;
parent::build();
$segments = \Request::segments();
$filename = ($file != '') ? basename($file, '.csv') : end($segments);
$filename = preg_replace('/[^0-9a-z\._-]/i', '',$filename);
$filename .= ($timestamp != "") ? date($timestamp).".csv" : ".csv";
$save = (bool) strpos($file,"/");
//Delimiter
$delimiter = array();
$delimiter['delimiter'] = isset($del['delimiter']) ? $del['delimiter'] : ';';
$delimiter['enclosure'] = isset($del['enclosure']) ? $del['enclosure'] : '"';
$delimiter['line_ending'] = isset($del['line_ending']) ? $del['line_ending'] : "\n";
if ($save) {
$handle = fopen(public_path().'/'.dirname($file)."/".$filename, 'w');
} else {
$headers = array(
'Content-Type' => 'text/csv',
'Pragma'=>'no-cache',
'"Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Disposition' => 'attachment; filename="' . $filename.'"');
$handle = fopen('php://output', 'w');
ob_start();
}
fputs($handle, $delimiter['enclosure'].implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $this->headers) .$delimiter['enclosure'].$delimiter['line_ending']);
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
if (in_array($column->name,array("_edit")))
continue;
$cell = new Cell($column->name);
$value = str_replace('"', '""',str_replace(PHP_EOL, '', strip_tags($this->getCellValue($column, $tablerow, $sanitize))));
$cell->value($value);
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
fputs($handle, $delimiter['enclosure'] . implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $row->toArray()) . $delimiter['enclosure'].$delimiter['line_ending']);
}
fclose($handle);
if ($save) {
//redirect, boolean or filename?
} else {
$output = ob_get_clean();
return \Response::make(rtrim($output, "\n"), 200, $headers);
}
}
protected function getCellValue($column, $tablerow, $sanitize = true)
{
//blade
if (strpos($column->name, '{{') !== false ||
strpos($column->name, '{!!') !== false) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = $this->parser->compileString($column->name, $array);
//eager loading smart syntax relation.field
} elseif (preg_match('#^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$#i',$column->name, $matches) && is_object($tablerow) ) {
//switch to blade and god bless eloquent
$_relation = '$'.trim(str_replace('.','->', $column->name));
$expression = '{{ isset('. $_relation .') ? ' . $_relation . ' : "" }}';
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$value = $this->parser->compileString($expression, $array);
//fieldname in a collection
} elseif (is_object($tablerow)) {
$value = #$tablerow->{$column->name};
if ($sanitize) {
$value = $this->sanitize($value);
}
//fieldname in an array
} elseif (is_array($tablerow) && isset($tablerow[$column->name])) {
$value = $tablerow[$column->name];
//none found, cell will have the column name
} else {
$value = $column->name;
}
//decorators, should be moved in another method
if ($column->link) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$array = $tablerow->getAttributes();
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = ''.$value.'';
}
if (count($column->actions)>0) {
$key = ($column->key != '') ? $column->key : $this->key;
$keyvalue = #$tablerow->{$key};
$routeParamters = \Route::current()->parameters();
$value = \View::make('rapyd::datagrid.actions', array('uri' => $column->uri, 'id' => $keyvalue, 'actions' => $column->actions,
'current_entity' => $routeParamters['entity']));
}
return $value;
}
public function getGrid($view = '')
{
$this->output = $this->build($view)->render();
return $this->output;
}
public function __toString()
{
if ($this->output == "") {
//to avoid the error "toString() must not throw an exception"
//http://stackoverflow.com/questions/2429642/why-its-impossible-to-throw-exception-from-tostring/27307132#27307132
try {
$this->getGrid();
}
catch (\Exception $e) {
$previousHandler = set_exception_handler(function (){ });
restore_error_handler();
call_user_func($previousHandler, $e);
die;
}
}
return $this->output;
}
public function edit($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->add('_edit', $label)->actions($uri, explode('|', $actions))->key($key);
}
public function getColumn($column_name)
{
if (isset($this->columns[$column_name])) {
return $this->columns[$column_name];
}
}
public function addActions($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->edit($uri, $label, $actions, $key);
}
public function row(\Closure $callable)
{
$this->row_callable[] = $callable;
return $this;
}
protected function sanitize($string)
{
$result = nl2br(htmlspecialchars($string));
return Config::get('rapyd.sanitize.num_characters') > 0 ? str_limit($result, Config::get('rapyd.sanitize.num_characters')) : $result;
}
public function rowCount()
{
return count($this->rows);
}
}
This is the source of a rapyd-laravel widget/package, not a custom code.
According to DataGrid/DataSet documentation, you can use many sources:
https://github.com/zofe/rapyd-laravel/wiki/DataSet
DataSet/DataGrid are presenters, you can retrieve all data of your data source using
{{ $item->field }} or {{ $row->field }} respectively
See the docs please
https://github.com/zofe/rapyd-laravel/wiki

joomla pagination shows same result on every page

I have page of articles with more than 5 results. 5 results are displayed per page. Pagination shows up. When I go to different pages however, every page has the same 5 results.
My getItems():
function getItems()
{
$params = $this->getState()->get('params');
$limit = $this->getState('list.limit');
// 5
if ($this->_articles === null && $category = $this->getCategory()) {
$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
$model->setState('params', JFactory::getApplication()->getParams());
$model->setState('filter.category_id', $category->id);
$model->setState('filter.published', $this->getState('filter.published'));
$model->setState('filter.access', $this->getState('filter.access'));
$model->setState('filter.language', $this->getState('filter.language'));
$model->setState('list.ordering', $this->_buildContentOrderBy());
$model->setState('list.start', $this->getState('list.start'));
$model->setState('list.limit', $limit);
$model->setState('list.direction', $this->getState('list.direction'));
$model->setState('list.filter', $this->getState('list.filter'));
// filter.subcategories indicates whether to include articles from subcategories in the list or blog
$model->setState('filter.subcategories', $this->getState('filter.subcategories'));
$model->setState('filter.max_category_levels', $this->setState('filter.max_category_levels'));
$model->setState('list.links', $this->getState('list.links'));
if ($limit >= 0) {
$this->_articles = $model->getItems();
if ($this->_articles === false) {
$this->setError($model->getError());
}
}
else {
$this->_articles=array();
}
$this->_pagination = $model->getPagination();
}
$filterResult = null;
return $this->_articles;
}
My populate state:
protected function populateState($ordering = null, $direction = null)
{
// Initiliase variables.
$app = JFactory::getApplication('site');
$pk = JRequest::getInt('id');
$this->setState('category.id', $pk);
// Load the parameters. Merge Global and Menu Item params into new object
$params = $app->getParams();
$menuParams = new JRegistry;
if ($menu = $app->getMenu()->getActive()) {
$menuParams->loadString($menu->params);
}
$mergedParams = clone $menuParams;
$mergedParams->merge($params);
$this->setState('params', $mergedParams);
$user = JFactory::getUser();
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
$groups = implode(',', $user->getAuthorisedViewLevels());
if ((!$user->authorise('core.edit.state', 'com_content')) && (!$user->authorise('core.edit', 'com_content'))){
// limit to published for people who can't edit or edit.state.
$this->setState('filter.published', 1);
/**
* Custom Author Filter
*/
if (JRequest::getVar('author')) {
$this->setState('filter.created_by', $this->getUserId(JRequest::getVar('author')));
}
// Filter by start and end dates.
$nullDate = $db->Quote($db->getNullDate());
$nowDate = $db->Quote(JFactory::getDate()->toMySQL());
$query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')');
$query->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
/**
* Custom Author Filter
*/
if (JRequest::getVar('author')) {
$query->where('(a.created_by = "' . $this->getUserId(JRequest::getVar('author')) . '")');
}
}
// process show_noauth parameter
if (!$params->get('show_noauth')) {
$this->setState('filter.access', true);
}
else {
$this->setState('filter.access', false);
}
// Optional filter text
$this->setState('list.filter', JRequest::getString('filter-search'));
// filter.order
$itemid = JRequest::getInt('id', 0) . ':' . JRequest::getInt('Itemid', 0);
$orderCol = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.filter_order', 'filter_order', '', 'string');
if (!in_array($orderCol, $this->filter_fields)) {
$orderCol = 'a.ordering';
}
$this->setState('list.ordering', $orderCol);
$listOrder = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.filter_order_Dir',
'filter_order_Dir', '', 'cmd');
if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', ''))) {
$listOrder = 'ASC';
}
$this->setState('list.direction', $listOrder);
//$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));
// set limit for query. If list, use parameter. If blog, add blog parameters for limit.
if ((JRequest::getCmd('layout') == 'blog') || $params->get('layout_type') == 'blog') {
$limit = $params->get('num_leading_articles') + $params->get('num_intro_articles') + $params->get('num_links');
$this->setState('list.links', $params->get('num_links'));
}
else {
$limit = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.limit', 'limit', $params->get('display_num'));
}
$this->setState('list.limit', $limit);
// set the depth of the category query based on parameter
$showSubcategories = $params->get('show_subcategory_content', '0');
if ($showSubcategories) {
$this->setState('filter.max_category_levels', $params->get('show_subcategory_content', '1'));
$this->setState('filter.subcategories', true);
}
$this->setState('filter.language',$app->getLanguageFilter());
$this->setState('layout', JRequest::getCmd('layout'));
}
My display function de view.html.php
function display($tpl = null)
{
$app = JFactory::getApplication();
$user = JFactory::getUser();
// Get some data from the models
$state = $this->get('State');
$params = $state->params;
$items = $this->get('Items');
$contactId = JRequest::getVar('author');
if($contactId){
$this->setUserId($contactId);
$this->setContactName($this->userId);
}
$category = $this->get('Category');
$children = $this->get('Children');
$parent = $this->get('Parent');
$pagination = $this->get('Pagination');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
JError::raiseError(500, implode("\n", $errors));
return false;
}
if ($category == false) {
return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
}
if ($parent == false) {
return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
}
// Setup the category parameters.
$cparams = $category->getParams();
$category->params = clone($params);
$category->params->merge($cparams);
// Check whether category access level allows access.
$user = JFactory::getUser();
$groups = $user->getAuthorisedViewLevels();
if (!in_array($category->access, $groups)) {
return JError::raiseError(403, JText::_("JERROR_ALERTNOAUTHOR"));
}
// PREPARE THE DATA
// Get the metrics for the structural page layout.
$numLeading = $params->def('num_leading_articles', 1);
$numIntro = $params->def('num_intro_articles', 4);
$numLinks = $params->def('num_links', 4);
// Compute the article slugs and prepare introtext (runs content plugins).
for ($i = 0, $n = count($items); $i < $n; $i++)
{
$item = &$items[$i];
$item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id;
// No link for ROOT category
if ($item->parent_alias == 'root') {
$item->parent_slug = null;
}
$item->event = new stdClass();
$dispatcher = JDispatcher::getInstance();
// Ignore content plugins on links.
if ($i < $numLeading + $numIntro) {
$item->introtext = JHtml::_('content.prepare', $item->introtext);
$results = $dispatcher->trigger('onContentAfterTitle', array('com_content.article', &$item, &$item->params, 0));
$item->event->afterDisplayTitle = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentBeforeDisplay', array('com_content.article', &$item, &$item->params, 0));
$item->event->beforeDisplayContent = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentAfterDisplay', array('com_content.article', &$item, &$item->params, 0));
$item->event->afterDisplayContent = trim(implode("\n", $results));
}
}
// Check for layout override only if this is not the active menu item
// If it is the active menu item, then the view and category id will match
$active = $app->getMenu()->getActive();
if ((!$active) || ((strpos($active->link, 'view=category') === false) || (strpos($active->link, '&id=' . (string) $category->id) === false))) {
// Get the layout from the merged category params
if ($layout = $category->params->get('category_layout')) {
$this->setLayout($layout);
}
}
// At this point, we are in a menu item, so we don't override the layout
elseif (isset($active->query['layout'])) {
// We need to set the layout from the query in case this is an alternative menu item (with an alternative layout)
$this->setLayout($active->query['layout']);
}
// For blog layouts, preprocess the breakdown of leading, intro and linked articles.
// This makes it much easier for the designer to just interrogate the arrays.
if (($params->get('layout_type') == 'blog') || ($this->getLayout() == 'blog')) {
$max = count($items);
// The first group is the leading articles.
$limit = $numLeading;
for ($i = 0; $i < $limit && $i < $max; $i++) {
$this->lead_items[$i] = &$items[$i];
}
// The second group is the intro articles.
$limit = $numLeading + $numIntro;
// Order articles across, then down (or single column mode)
for ($i = $numLeading; $i < $limit && $i < $max; $i++) {
$this->intro_items[$i] = &$items[$i];
}
$this->columns = max(1, $params->def('num_columns', 1));
$order = $params->def('multi_column_order', 1);
if ($order == 0 && $this->columns > 1) {
// call order down helper
$this->intro_items = ContentHelperQuery::orderDownColumns($this->intro_items, $this->columns);
}
$limit = $numLeading + $numIntro + $numLinks;
// The remainder are the links.
for ($i = $numLeading + $numIntro; $i < $limit && $i < $max;$i++)
{
$this->link_items[$i] = &$items[$i];
}
}
$children = array($category->id => $children);
//Escape strings for HTML output
$this->pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
$this->assign('maxLevel', $params->get('maxLevel', -1));
$this->assignRef('state', $state);
$this->assignRef('items', $items);
$this->assignRef('category', $category);
$this->assignRef('children', $children);
$this->assignRef('params', $params);
$this->assignRef('parent', $parent);
$this->assignRef('pagination', $pagination);
$this->assignRef('user', $user);
$this->_prepareDocument();
parent::display($tpl);
}
If i print the contents of $pagination in the view.html.php here:
$this->_prepareDocument();
echo '<pre>'; print_r($pagination); exit();
parent::display($tpl);
I get the following results:
In my template file I echo the pagination:
<?php echo $this->pagination->getPagesLinks(); ?>
By the way, clicking on 'next' does change the url into ...?start=5.
This line in populateState is commented out
$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));
Uncomment it change it tot get the "start" parameter:
$this->setState('list.start', JRequest::getVar('start', 0, '', 'int'));

Resources