How to get proper collection in magento grid? - mysql

I have a custom grid tab in magento category with separate table to store data.
This is table with data:
When I filter by 'Yes' under first column. It does return associated rows with ID (284 & 285) but when I select 'No', it returns IDs (281-283), it's supposed to return 283 only which is the only stream not configured already.
And when I select ANY, it returns all associated and not associated with duplicate streams to select.
What I need is show each streams once only and work with first column filter.
I think I have incorrect joins with another table which holds all the streams (groups).
This is another table
protected function _prepareCollection()
{
if ($this->getCategory()->getId()) {
$this->setDefaultFilter(array('selected_tcategoryacl'=>1));
}
/* #var $collection Technooze_Tcategoryacl_Model_Mysql4_Tcategoryacl_Collection */
$collection = Mage::getModel('tcategoryacl/tcategoryacl')->getCollection();
$collection->getSelect()->joinRight('school_group', 'school_group_id=group_id');
$collection->addFieldToFilter('school_group_status', 1);
//$collection->getSelect()->group('school_group.school_group_id');
$collection = $this->insertFakeIdsToCollection($collection);
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _addColumnFilterToCollection($column)
{
$tcategoryaclIds = $this->_getSelectedTcategoryacl();
switch($column->getId()){
case 'selected_tcategoryacl':
if (empty($tcategoryaclIds)) {
$tcategoryaclIds = 0;
}
//$this->getCollection()->addFieldToFilter('category_id', $this->getCategory()->getId());
if ($column->getFilter()->getValue()) {
$this->removeRightJoin();
$this->getCollection()->clear()->addFieldToFilter('tcategoryacl_id', array('in'=>$tcategoryaclIds));
} elseif(!empty($tcategoryaclIds)) {
$this->getCollection()->clear();
$this->getCollection()->addFieldToFilter('tcategoryacl_id', array('nin'=>$tcategoryaclIds));
//$this->getCollection()->addFieldToFilter('school_group.school_group_id', array('nin'=>$this->_getSelectedSchoolGroupIds()));
$this->setCollection($this->insertFakeIdsToCollection($this->getCollection()));
}
break;
/*case 'allow_from':
case 'allow_to':
$this->getCollection()->addFieldToFilter($column->getId(), array('like'=>$column->getFilter()->getValue()));
break;*/
default: parent::_addColumnFilterToCollection($column);
}
return $this;
}
private function removeRightJoin(){
$this->getCollection()->clear()->getSelect()->reset('RIGHT JOIN');
}
protected function insertFakeIdsToCollection($collection)
{
$i = 0;
foreach($collection as $v){
// lets have fake ids for empty tcategoryacl_id, so checkbox can be selected
if(!$v->getData('tcategoryacl_id')){
$v->setData('tcategoryacl_id', '0' . $this->getCategory()->getId() . $i++);
$v->setId($v->getData('tcategoryacl_id'));
}
// lets auto select different groups in each row
if(!$v->getData('group_id')){
$v->setData('group_id', $v->getData('school_group_id'));
}
}
return $collection;
}
/**
* #return array
*/
protected function _getSelectedSchoolGroupIds()
{
$selected_tcategoryacl = array();
$category = $this->getCategory();
$collection = Mage::getModel('tcategoryacl/tcategoryacl')->getCollection();
$collection->addFieldToFilter('category_id', $category->getId());
foreach($collection as $v)
{
$selected_tcategoryacl[] = $v->getGroupId();
}
return $selected_tcategoryacl;
}
/**
* #return array
*/
protected function _getSelectedTcategoryacl()
{
$selected_tcategoryacl = array();
$category = $this->getCategory();
$collection = Mage::getModel('tcategoryacl/tcategoryacl')->getCollection();
$collection->addFieldToFilter('category_id', $category->getId());
foreach($collection as $v)
{
$selected_tcategoryacl[] = $v->getTcategoryaclId();
}
return $selected_tcategoryacl;
}
Update
added code on repo - https://github.com/dbashyal/Tcategory_ACL/blob/master/app/code/community/Technooze/Tcategoryacl/Block/Adminhtml/Catalog/Category/Tab/Tcategoryacl.php

Related

Laravel saves child record, but sets foreign key to null

This has got to be a simple fix, as I have done this many times before. But as it stands I am completely stumped. I use the following code to save a parent object Unknown_Tag and its many children.
Method:
public function saveUnknown(Request $request)
{
$url = $request->url;
$tag = new Unknown_Tag();
$tag->url = $url;
$protocol =
substr($url, 0, strpos($url, ':'));
$tag->protocol = $protocol;
$domain =
parse_url($url, PHP_URL_HOST);
$tag->domain = $domain;
$tag->save();
//get the path
$Path = parse_url($url, PHP_URL_PATH);
if ($Path) {
$splitPath = substr($Path, 1);
$paths = explode('/', $splitPath);
foreach ($paths as $p) {
$path = new Path();
$path->path = $p;
$tag->Paths()->save($path);
}
}
//get Queries
$splitQuery = parse_url($url, PHP_URL_QUERY);
if ($splitQuery) {
$queries = explode('&', $splitQuery);
foreach ($queries as $q) {
$query = new Query();
$q = substr($q, 0, strpos($q, '='));
IF (SUBSTR($q, -1) != ' ') {
$q .= ' ';
}
$query->var = $q;
$value = $q = preg_replace('/^[^=]*:/', '', $q);
$query->value = $value;
$tag->Queries()->save($query);
}
}
}
The Parent Object
class Unknown_Tag extends Model
{
protected $table = 'unknown_tags';
public $timestamps = false;
public function Paths()
{
return $this->hasMany('App\Path', 'tag_id', 'ID');
}
public function Queries()
{
return $this->hasMany('App\Query', 'tag_id', 'ID');
}
}
The Child objects
class Query extends Model
{
protected $table = 'queries';
public $timestamps = false;
public function Tag()
{
return $this->belongsTo('App\Unknown_Tag', 'tag_id', 'ID');
}
}
class Path extends Model
{
protected $table = 'paths';
public $timestamps = false;
public function Tag()
{
return $this->belongsTo('App\Unknown_Tag', 'tag_id', 'ID');
}
}
When I run all this via a post request, The Parent and all the children are saved properly, but all the child objects have a foreign key that is set to null. If I manually change the foreign key to what it should be, everything works just fine, so I am fairly sure this is not a problem with my database. Can anyone see the obvious that I am missing here?
EDIT:Just to be clear, this returns no errors
If anyone ever sees this, laravel assumes the default primary key is 'id'. I had set mine to 'ID', so I had to let laravel know by using
protected $primaryKey = 'ID';
in my Unknown_tag definition

Method chainning for join table with pagination on CI 3

I create a core class named MY_Model that extends CI_Model. In this class, I create a method chaining to get all record with pagination like this :
// Take record with paging.
public function get_all_paged()
{
// get argument that passed
$args = func_get_args();
// get_all_paged($offset)
if (count($args) < 2) {
$this->get_real_offset($args[0]);
$this->db->limit($this->_per_page, $this->_offset);
}
// get_all_paged(array('status' => '1'), $offset)
else {
$this->get_real_offset($args[1]);
$this->db->where($args[0])->limit($this->_per_page, $this->_offset);
}
// return all record
return $this->db->get($this->_tabel)->result();
}
So , I just used like this on my controller,
for example
public function index($offset = NULL) {
$karyawan = $this->karyawan->get_all_paged($offset); //get all
}
I am realy confuse to get all record using join, I know join in CI like this :
public function get_all_karyawan() {
$this->db->select('tb_1 , tb_2');
$this->db->from('tb_1');
$this->db->join('tb_2', "where");
$query = $this->db->get();
return $query->result();
}
How to make it into chain in MY_Model?
Any help it so appreciated ...
The good thing in query builder, you can chain your db methods, till get(). So you can define, selects, where queries, limits in different ways.
For example:
public function category($category)
{
$this->db->where('category_id', $category);
return $this;
}
public function get_posts()
{
return $this->db->get('posts')->result();
}
And you can get all posts:
$this->model->get_posts();
Or by category:
$this->model->category(2)->get_posts();
So upon this, in your model:
public function get_all_karyawan() {
$this->db->select('tb_1 , tb_2');
$this->db->join('tb_1', "where");
// Here you make able to chain the method with this
return $this;
}
In your controller:
public function index($offset = NULL) {
$karyawan = $this->karyawan->get_all_karyawan()->get_all_paged($offset);
}

Dispaly records from database in magento

I am using this code in my Grid.php to display records from a single tabel 'paypal_payment_transaction':
protected function _prepareCollection()
{
$db = Mage::getSingleton('core/resource')->getConnection('core_write');
$query = "SELECT transaction_id,txn_id,additional_information,created_at,user_id,reference_txn
FROM `paypal_payment_transaction`
LIMIT 0 , 30";
$result = $db->query($query);
// Get count of affected rows
$affected_rows = $result->rowCount();
$orders = $result->fetchAll($sql);
foreach($orders as $order)
{
echo "<pre>"; print_r($order);
}
}
I need this query in magento way:
may be like this
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('sales/order_collection')
SOME QUERY TO SELECT RECORD FROM TABEL 'paypal_payment_transaction'
;
$this->setCollection($collection);
parent::_prepareCollection();
return $this;
}
So that I can display it in grid accordingly i.e. in :
protected function _prepareColumns()
{
-------------------
------------------
}
Try this -
protected function _prepareCollection()
{
$collection = Mage::getModel('paypal/payment_transaction')->getCollection();
$this->setCollection($collection);
parent::_prepareCollection();
return $this;
}
you can try the following code
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('payment/transaction')
$Collection->addFieldToSelect('transaction_id');
$this->setCollection($collection);
parent::_prepareCollection();
return $this;
}
Thanks

Issue with a Table Model

I've been having a problem with a table model recently and I can't really explain why this happens. I want to select everything from a table and return it in a descending order. But when I try to display it nothing shows up:
Code:
<?php
//Will be used at a later date
namespace Blog\Model\Table;
use Zend\Db\TableGateway\TableGateway;
class Blog extends TableGateway
{
public function __construct($adapter)
{
parent::__construct('posts', $adapter);
}
public function displayPosts()
{
$adapter = $this->getAdapter();
$result = $adapter->query('SELECT * FROM `posts` ORDER BY `date_added` DESC');
return $result;
}
}
Result:
But when I add an $id argument it shows the data:
Code:
<?php
//Will be used at a later date
namespace Blog\Model\Table;
use Zend\Db\TableGateway\TableGateway;
class Blog extends TableGateway
{
public function __construct($adapter)
{
parent::__construct('posts', $adapter);
}
public function displayPosts($id = 6)
{
$adapter = $this->getAdapter();
$result = $adapter->query('SELECT * FROM `posts` WHERE `post_id` = ?', array($id));
return $result;
}
}
Result:
It's weird that it works with an argument and not without, any ideas?
You needed to order it by post_id
public function displayPosts()
{
$adapter = $this->getAdapter();
$result = $adapter->query('SELECT * FROM `posts`')->order(array('post_id' => 'DESC'));
return $result;
}

Gets Data From Mssql to Mysql Database Using PDO

I'm getting data from my accounting program in Windows Platform to my PHP Script. I'm transferring data from mssql to mysql. I decided to use PDO. I have a problem with transition. How can i supply two connection simultaneously ?
Here is my own PDO Class.
class Database {
protected $_host = "***********";
protected $_engine = "mysql";
protected $_dbuser = "***********";
protected $_dbpassword = "***********";
protected $_db = "***********";
protected $_sql;
protected $pdo;
/* #desc This Function is Setting SQL Connection
* #return SQL Connection
*
*/
protected function getPdo()
{
if ($this->pdo === NULL) {
try {
$dsn = $this->_engine.':dbname='.$this->_db.';host='.$this->_host.';charset=utf8';
$this->pdo = new PDO($dsn, $this->_dbuser, $this->_dbpassword, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
));
//$this->pdo->setAttribute();
//$this->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
return $this->pdo;
}
/* #desc This Function is Preparing Sql Statement For Query
* #return array Returns PDO Object Query
*
*/
public function query($sql)
{
return $this->_sql = $this->getPdo()->prepare($sql);
}
/* #desc This Function is for Binding Values into SQL Statements
* #return Binded SQL Statements
*
*/
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->_sql->bindValue($param, $value, $type);
}
/* #desc This Function Execute Query
* #return SQL Execution
*
*/
public function execute($values = NULL){
return (!isset($values)) ? $this->_sql->execute() : $this->_sql->execute($values);
}
/* #desc This Function Execute Query and Fetch Multiple Result
* #return array Returns Array of Table Rows. Array is multidimensional
*
*/
public function queryResults(){
$this->execute();
return $this->_sql->fetchAll(PDO::FETCH_ASSOC);
}
/* #desc This Function Execute Query and Fetch Only Single Result
* #return array Returns Array of Table Row. Array is not multidimensional.
*
*/
public function queryResult(){
$this->execute();
return $this->_sql->fetch(PDO::FETCH_ASSOC);
}
public function queryColumn($index = NULL){
$index = (isset($index)) ? intval($index) : 0;
$this->execute();
return $this->_sql->fetchAll(PDO::FETCH_COLUMN,$index);
// $this->execute();
// return $this->_sql->fetchAll(PDO::FETCH_COLUMN);
}
/* #desc This Function Returns Effected Row Count during Update, Delete and Insert
* #return int Returns Effected Row Count
*
*/
public function effected(){
return $this->_sql->rowCount();
}
/* #desc This Function Returns Effected Row Count during Update, Delete and Insert
* #return int Returns Effected Row Count
*
*/
public function rowCount(){
return count($this->queryResults());
}
public function lastID(){
return $this->_sql->lastInsertId();
}
You need to create 2 instances of PDO class - one for MSSQL and one for MySQL.