accessing data linked by foreign key in site view of custom component - joomla

In my custom component, in site view, I have a list of countries (view: countries). Clicking on a country, another view is displayed (view: persons) showing all persons living in that country.
Now, in persons view, I want to display the country's name and flag.
So I want to add a function getCountry() in ...site/models/persons.php:
public function getCountry() {
$db = $this->getDBO();
$id = $this->state->get("filter.country");
$sql = "SELECT * FROM #__cnlp_persons_country WHERE id = $id";
$db->setQuery($sql);
$country = $db->loadResult();
// var_dump($country);
return $country;
}
Then, I added to .../site/views/persons/view.html.php:
class Cnlp_personsViewPersons extends JView
{
protected $items;
protected $state;
protected $params;
protected $country; // <--- I added this
...
public function display($tpl = null)
{
$app = JFactory::getApplication();
$this->state = $this->get('State');
$this->items = $this->get('Items');
$this->params = $app->getParams('com_cnlp_trainers');
$this->country = $this->get('Country'); // <--- I added this
(...)
Result: I thought I could then in ---/site/views/persons/tmpl/default.php something like...
<h1><?php echo $this->country->name; ?></h1>
<img src="<?php echo $this->country->flag; ?>" />
...but I get no output...
What did I do wrong?

$db->loadResult(); is used to load a single value results (for example if you would only want to select the country name or something like this), but in your query you're selecting an entire row, so you should use one of theese:
$db->loadRow(); // returns an indexed array from a single record in the table
$db->loadAssoc(); // returns an associated array from a single record in the table
$db->loadObject(); // returns a PHP object from a single record in the table:
You can read more about this here (it's joomla 1.5 documentation, but it's same for 2.5 and 3)

Related

Get data from database with condition and show it in a view

This is the data that I have in database
This is what I want to make in the view.blade.php
What I want to do is I want to get the data from the database, if the data inside the column is 1, I want to get the column name as you can see in image 2, but there could be more than 1 column name because the column with data can be column A,B,C... etc.. and I want to show the student name and the subject (a,b,c... etc) if the data in it is '1' in the view. I stuck on how to get all those subject A,B,C.. this is the code that I have written, but it is incomplete because I don't know what to add on it to make it as what I have mentioned above. Hopefully, someone can help me. Thanks in advance
if($row->'A'=='1'){i dont know what should i put here so that i cant get the column name 'A' and print it in view.blade.php}
Assuming your table in database is student_details, create an eloquent model StudentDetail inside app/models/StudentDetail.php :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class StudentDetail extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'student_details';
/**
* Get subjects in the view
*
* #return string
*/
public function getSubjects()
{
$subjects = [];
$subjects[] = $this->A == 1 ? 'A' : null;
$subjects[] = $this->B == 1 ? 'B' : null;
$subjects[] = $this->C == 1 ? 'C' : null;
$subjects = array_filter($subjects);
return implode(',', $subjects);
}
}
Then you can retrieve data in your controller :
public function view()
{
$studentDetails = StudentDetail::get();
return view('view.path', compact('studentDetails'));
}
And inside view you can do :
#foreach($studentDetails as $detail)
{{ $detail->name }} : {{ $detail->getSubjects() }}
#endforeach
You can use appended property as well, I have not used that because appended property is added every-time when model is instantiated. I believe having it in a function makes it flexible to use as and when needed.
Okay i tried it bit different way it's not proper but it will give you desired output you want :-
Route::get('/test',function(){
$query = TestTable::all();
$calculateData = [];
foreach ($query as $key){
$subjects = '';
if($key->A === 1){
$subjects .= 'A';
}
if($key->B === 1){
$subjects .= 'B';
}
if($key->C === 1){
$subjects .= 'C';
}
$calculateData[] = [$key->name,$subjects];
}
foreach ($calculateData as $key){
dump("NAME : " . $key[0]."Subject : " . $key[1]);
}
dd("STOP");
})->name('test');

Laravel 5.1 Command empty table

I'm using a command to add products from an API to my database using the following code
class UpdateCatalog extends Command {
protected $name = 'catalog:update';
protected $description = 'Command description.';
public function __construct()
{
parent::__construct();
}
public function fire()
{
$products = Api::productsGetProducts();
foreach($products as $product)
{
$detail = Api::productsGetProduct($product['id']);
$product = new Product();
$product->id = $detail->getId();
$product->external_id = $detail->getExternalId();
$product->name = $detail->getName();
$product->description = $detail->getDescription();
$product->thumbnail = $detail->getThumbnail();
$product->price = $detail->getPrices()[0]['price_excl_vat'];
$product->vat = $detail->getVat();
$product->save();
}
}
}
Now I'm wondering if it's possible to empty the table prior to filling it again.
Thank you!
Do you mean you want to empty your Product database table?
This can be done with truncate like this:
Product::truncate();
Note: This will remove all rows and reset the auto-incrementing ID to zero

Magento. How to link store_id to the attribute in the custom EAV Model

I am using this tutorial on adding new EAV Model in Magento:
http://inchoo.net/ecommerce/magento/creating-an-eav-based-models-in-magento/
Everything works fine except all my attributes are saving with "store_id = 0" when I do this part of code:
$phonebookUser = Mage::getModel('inchoo_phonebook/user');
$phonebookUser->setFristname('John');
$phonebookUser->save();
I am wondering is there any clear way to set store ID on save EAV Entity Attributes.
Thanks.
You can only set values for a specific store only after you added the values for store id 0.
Here is an example.
//create default values
$phonebookUser = Mage::getModel('inchoo_phonebook/user');
$phonebookUser->setFristname('John');
$phonebookUser->save();
//remember the id of the entity just created
$id = $phonebookUser->getId();
//update the name for store id 1
$phonebookUser = Mage::getModel('inchoo_phonebook/user')
->setStoreId(1)
->load($id); //load the entity for a store id.
$phonebookUser->setFristname('Jack'); //change the name
$phonebookUser->save(); //save
I have override the functions in my resource model to work with store_id and it is worked for me but I suggest that this is not the best solution.
protected function _saveAttribute($object, $attribute, $value)
{
$table = $attribute->getBackend()->getTable();
if (!isset($this->_attributeValuesToSave[$table])) {
$this->_attributeValuesToSave[$table] = array();
}
$entityIdField = $attribute->getBackend()->getEntityIdField();
$data = array(
'entity_type_id' => $object->getEntityTypeId(),
$entityIdField => $object->getId(),
'attribute_id' => $attribute->getId(),
'store_id' => $object->getStoreId(), //added this
'value' => $this->_prepareValueForSave($value, $attribute)
);
$this->_attributeValuesToSave[$table][] = $data;
return $this;
}
protected function _getLoadAttributesSelect($object, $table)
{
$select = $this->_getReadAdapter()->select()
->from($table, array())
->where($this->getEntityIdField() . ' =?', $object->getId())
->where('store_id in (?)', array($object->getStoreId(), 0)); //added this
return $select;
}
also I have added this code to the constructor of my entity model:
if (Mage::app()->getStore()->isAdmin()) {
$this->setStoreId(Mage::app()->getRequest()->getParam('store', 0));
}
else{
$this->setStoreId(Mage::app()->getStore()->getId());
}
Override the _getDefaultAttributes() method in your resource model like this:
protected function _getDefaultAttributes()
{
$attributes = parent::_getDefaultAttributes();
$attributes[] = "store_id";
return $attributes;
}
This should work if you have only one value for store_id per your model's entity.

zend Pagination without fetching query again for each page

Is it possible to use zend pagination without calling the query every time i request a page from the pager?
When I hit a page number from the pager a request to the zzAction below is done and the query is fetched again. My query is huge and I don't want to fetch the query all over again. Am I missing something in the code.
Code:
Controller:
public function getOnePageOfEntries($array, $page=1) {
$paginator = Zend_Paginator::factory($array);
$paginator->setItemCountPerPage(6);
$paginator->setCurrentPageNumber($page);
return $paginator;
}
public function zzAction() {
...
$tt= $this->yyObject->xx(....);
$paginator = $this -> getOnePageOfEntries($tt, $page);
$this->view->paginator = $paginator;
}
Model:
public function xx(...){
try{
...
$stmt = $this->prepare("CALL sp_yy(...)");
....
$stmt->execute();
$result = $stmt->fetchAll();
if (is_null($result)) {
return null;
}
return $result;
}catch (ErrorsException $obj){
echo $obj;exit;
}//end try
}
View:
<?php
$config = Zend_Registry::get('appsConfig');
?>
<?php if (count($this->paginator)){ ?>
<?php foreach($this->paginator as $cc){ ?>
<?php echo $cc['id'] . '/';?>
<?php } ?>
<?php } ?>
<?php echo $this->paginationControl($this->paginator,
'Sliding','ff/my_pagination_control.phtml'); ?>
using Zend_Paginator_Adapater_DbSelect();
example:
$adapter = new Zend_Paginator_Adapter_DbSelect($data); //$data is database query
$pagination = new Zend_Paginator($adapter);
See more here:
Zend_Paginator_Adapter_DbSelect
Your current code artificially limits the utility of the array adapter and forces you to execute the whole query for every page. What you need to accomplish in your controller actions that consume this paginator is to only execute the query if the data doesn't already exist. Maybe something similar to:
//consider this to psuedocode as it has not been tested a represents an idea
public function zzAction()
{
//get page number
$page = $this->getRequest()->getParam('page');
//set session namespace, probably better to do this in init() method or bootstrap
$session = new Zend_Session_Namespace('paged')
//test for presence of persisted array
if (!isset($session->paginator)) {
//perform query
$arrayToPage = $this->yyObject->xx(....);
//persist result array
$session->paginator = $arrayToPage;
} else {
//retrieve persisted array
$arrayToPage = $session->paginator;
}
$paginator = $this -> getOnePageOfEntries($arrayToPage, $page);
$this->view->paginator = $paginator;
}
Using the DbTableSelect or DbSelect paginator adapter is often far more effiecient as it only queries for the data need to populate a specific page. This is very useful when your user wants to go form page 1 to page 7 ...
Another consideration when using a paginator is custom entity models. This is fairly easy to deal with in ZF:
<?php
class Record_Model_Paginator_Record extends Zend_Paginator_Adapter_DbTableSelect
{
//override getItems to customize the adapter to use a specific mapper to create entities
public function getItems($offset, $itemCountPerPage)
{
$rows = parent::getItems($offset, $itemCountPerPage);
$record = array();
foreach ($rows as $row) {
//initiate mapper
$recordEntity = new Application_Model_Mapper_Record();
//create entity models
$record[] = $recordEntity->createEntity($row);
}
//returns an array of objects, similar to a Zend_Db_Rowset object
return $record;
}
}
I hope this helps.

Codeigniter num_row returns "array" instead of number

Alright, Im trying to count all the rows where "Membership_Status" = Active. The result I get right now is "Array" instead of a number.
Here is my model
class Report_model extends Model
{
function count_members()
{
$query = $this->db->get_where('Membership', array('Membership_Status' => 'Active'));
return $query->num_rows();
}
}
Here is my controller
class Report extends Controller {
function YTD_report()
{
$data['main_content'] = 'report_membership_view';
$this->load->view('includes/template', $data);
}
}
Here is my view
report_model->count_members();
echo $total;
?>
My result is Array, where according to the db info, it should be 4.
What can I do/change to get it to display the proper number?
thanks
the $data array your passing to the view will create one variable for each key to be used by view...
So your controler once the model is loaded, you should do:
$data['total'] = $this->Report_model->count_members();
Then in the view you can use the $total variable like this:
<?php echo $total; ?>

Resources