Json call in joomla 2.5 component - json

I'm making a joomla 2.5 component and i trying to set in model or controller (what's the most appropriate ?) a json response of my DB request (for later get the json with angularJS).
Here's my model (with DB response):
<?php
defined('_JEXEC') or die();
jimport( 'joomla.application.component.modelList' );
class MediastoreModelList extends JModelList
{
function getListQuery()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id, type, designation', 'marque', 'prix');
$query->from('produits');
return $query;
}
}
My empty controller:
<?PHP
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
class MediastoreController extends JController
{
}
My view
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
jimport( 'joomla.application.component.view' );
class MediastoreViewList extends JView
{
function display($tpl = null)
{
$this->items = $this->get('items');
parent::display($tpl);
}
}
and my template
<?php
defined('_JEXEC') or die('Restricted access');
JHTML::script('media/com_mediastore/js/angular.min.js');
JHTML::script('media/com_mediastore/js/app.js');
?>
<?php
echo $this->items;
?>
<div class="content">
<p>Nothing</p>
</div>
How can i do that ?
Thanks a lot,
Antoine

Bit late .....
Hi I am working on something similar.
In your views (sitepart) add an other file called view.raw.php.
You can browse to this file by appending 'format=raw' at the end of the url.
For example: if your component view page in the browser is 'http://test.com/test( IF SEF is on ) then after appending th url shoul be like this
http://test.com/test?format=raw and in case SEF is not on the use & instead of ?
You can use this URL in the angularjs for http.get service.
In view.raw.php file make sure you just echo the results rather than parent::display($tpl);.
This did work for me.
PS: I am using angualrjs too but want to use the component with many menu items and the url keeps changing so am stuck on that part.
Hope this solves your issue.
Regards,
Jai

Related

cakePHP3 pass variable from controller to view

I have a problem when passing a variable from Controller to view in CakePHP3.
File FincasController.php: I have created a public Method to make a report and be able to pass to a Template I have also created.
public function worklist()
{
$worklist = TableRegistry::get('Fincas');
$query = $worklist
->find()
->select(['id', 'prov', 'municipio', 'paraje', 'poligono', 'parcela', 'f_ult_poda' , 'f_ult_recog' ]);
foreach ($query as $worklist) {
if ( $worklist->f_ult_poda > $worklist->f_ult_recog )
debug($worklist); //it works fine
}
$this->set('finca', $this->$query); //I have tried also $this->$worklist
}
File Template\Fincas\worklist.ctp :
<?php debug($finca);?>
Thanks a lot
$query it justa a variable, it's not an attribute of your FincasControllerõ. Why are you using$this`?
simply
$this->set('finca', $query);

Write database queries in Magento custom module

I created a custom module in my Magento. This is working good. My module's name is mymodule.
Mymodule.php
class Myshop_Mymodule_Block_Mymodule extends Mage_Core_Block_Template
{
public function myfunction()
{
return "Hello User";
}
}
The path of the Mymodule.php file is C:\wamp\www\magento\app\code\local\Myshop\Mymodule\Block.
Now I want to display some data from database. For example I would like to display the admin's email id. How can I display this??
I tried like this.
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
//database write adapter
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $read->fetchAll("select email from admin_user where user_id= 1");
var_dump($result);
I write these lines in Mymodule.php inside myfunction. But nothing displayed(display only "Hello User").
So my question is how to display or write database queries in magento custom module.
Please someone help me..Any help is really appreciable..
We generally avoid using adapters when magento by default provides models for the basic tables. In your case, you can fetch the admin details using following :
<?php
$userDetails = Mage::getModel('admin/user')->load(1);
//where 1 is your admin user id
echo $userDetails->getEmail();
?>
Hence, your function can be modified as :
<?php
class Myshop_Mymodule_Block_Mymodule extends Mage_Core_Block_Template
{
public function myfunction()
{
$userDetails = Mage::getModel('admin/user')->load(1);
return $userDetails->getEmail();
}
}
You can get data from database in magento as
$collection = Mage::getModel("mumodule/mymodule")->getCollection();
foreach($collection as $data){
..Your Code ..
}

Laravel Select Query within helper file

I'm coming from codeigniter background. Unlike codeigniter helper directory, i just created helper directory within app directory of Laravel. Just want to know how to execute query within this common function. Here is my codeigniter function.
function show_menu($primary_key_col, $parent_id, $sort_order)
{
$output = "";
$ci =& get_instance();
$ci->db->select("*");
$ci->db->where('is_active', "Y");
$ci->db->where('is_delete', "N");
$ci->db->where('parent_id', $parent_id);
($sort_order!="")?$ci->db->order_by($sort_order, "ASC"):"";
$query = $ci->db->get('tbl_cms_menus');
foreach ($query->result() as $row){
$output .= '<option value="'.$row->$primary_key_col.'">'.$indent.$row->menu_name.'</option>';
}
return $output;
}
I tried something like this in laravel file. but this code did't give me any result. Please tell me where i'm doing wrong in this code. thanks
function databaseTable()
{
$table = DB::table('tbl_cms_menus');
$get_rows = $table->get();
$count_rows = $table->count();
if($count_rows > 0){
foreach ($get_rows as $tbl)
{
echo $tbl->menu_name;
}
}
}
This code will rot so hard that it shipped pre-rotten.
But, if you want to just.. ram it into the app all dry like that.. then add something like this to your base controller class...
$whatever = crazyChainingStuff;
foreach ($whatever ...) { $topMenu .= ... }
View::share('topMenu', $topMenu);
If you want to learn how to write code that will do less damage to your company and your clients then I recommend starting by watching Uncle Bob's "Fundamentals" videos. At least the first 5-6. http://cleancoders.com
It looks like you are trying to generate a drop-down/select with some data from your database, in this case, you should pass the data required for the drop-down/select from your controller to the view where you have written your HTML, for example, in your view, you may have a select like this:
echo Form::select('cms_menu', $cms_menu, Input::old('cms_menu'));
Or this (If you are using Blade):
{{ Form::select('cms_menu', $cms_menu, Input::old('cms_menu')) }}
From your controller you should pass the $cms_menu which should contain the menu-items as an arrtay and to populate that array you may try something like this:
$menuItems = DB::table('tbl_cms_menus')->lists('menu_name','id');
return View::make('your_view_name', array('cms_menu' => $menuItems));
Also, you may use something like this:
// Assumed you have a Page model
$menuItems = Page::lists('menu_name', 'id');
return View::make('your_view_name', array('cms_menu' => $menuItems));
You may also read this article which is about building a menu from database using view composer (More Laravelish way). Read more about Form::select on documentation.
It was too late to give an answer. I was also from CodeIgniter background and when I learnt Laravel then first I try to find how can I write a query in Helper. My Team leader helped me.
I have converted your code in a helper function.
function show_menu($primary_key_col, $parent_id, $sort_order)
{
$query = DB::table('tbl_cms_menus')
->select('*')
->where('is_active', '=', 'Y')
->where('is_delete', '=', 'N')
->where('parent_id', '=', $parent_id);
($sort_order != "")? $query->orderBy($sort_order, "ASC") : "";
$resultData = $query->get()->toArray();
}
Here $resultData will be array format. Now, you can create a foreach loop according to your requirement.

Codeigniter 1-many db query on two tables which call for nested loops

I've read through a couple posts which are really close to the same question I am about to ask, but I'm still not grasping the MVC way. One example was close and titled "Codeigniter db query on two tables", but I'm getting the "Undefined property" errors which reinforces that fact I'm not calling objects properly. I would prefer not to use DataMapper simply because if I need to go out and get additional classes, then I might just go back to the procedural coding route. I was just a little excited on understanding how this framework implementation works.
I have two tables, lets call one "apps" and the other would be "mappings". "Apps" are applications which use apache as a reverse proxy configuration like this:
ProxyPass /mapping/ https:///
ProxyPassReverse /mapping/ https:///
Some of the apps could request multiple reverse proxy mappings, so its a 1-many design.
My objective is to use a select statement for the apps table then print out every column I desire from that table:
for example, I currently have two application defined in my "apps" table, in which one of the applications has two reverse proxy mappings,and the other has one. The prxypass lines below the data from the apps table would be coming from the apps_mapping table.
App: App ABC
Owner: ABC Team
Date Requested: 2013-10-27
ProxyPass /ABC-Resource/ https://<to-some-internal-URL>/
ProxyPassReverse /ABC-resource/ https://<to-some-internal-URL>/
App: App XYZ
Owner: XYZ Team
Date Requested: 2013-10-27
ProxyPass /XYZ-mapping/ https://<to-some-internal-URL>/
ProxyPassReverse /XYZ-mapping/ https://<to-some-internal-URL2>/
ProxyPass /anothermapp/ https://<to-some-internal-URL>/
ProxyPassReverse /anothermapping/ https://<to-some-internal-URL2>/
I've tried to model my first attempt of using CodeIgniter by way of modifying their tutorial provided by the CodeIgniter example in their user_guide.
Now what I haveis.
Model Class:
<?php
class Prp_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
//GET APP THE ROWs FROM THE apps TABLE
public function get_appsUsingPrp()
{
$query = $this->db->get('apps');
return $query->result_array();
}
//GET THE MAPPINGS FROM THE apps_mappings TABLE
//FOR EACH APP BY WAY OF UNIQUE id IN THE appsTABLE
public function get_prpMappings($id = FALSE)
{
$query = $this->db->get_where('apps_mappings', array('resourceID' => $id));
return $query->result_array();
}
?>
for the above class, instead of using a return function on get_prpMappings() should I be putting it in a variable? Even then, how would one supply a value for the $id in the code called int he views page?
Controller Class
<?php
class Prp extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('prp_model');
}
public function index()
{
$data['apps'] = $this->prp_model->get_prp();
$data['mappings'] = $this->prp_model->get_prpMappings($id);
$data['title'] = 'PRP archive';
$this->load->view('templates/header', $data);
$this->load->view('prp/index', $data);
$this->load->view('templates/footer');
}
public function view($id)
{
$data['apps'] = $this->prp_model->get_prp();
$data['mappings'] = $this->prp_model->get_prpMappings($id);
}
}
View
<?php
print_r($apps);
print_r($mappings);
foreach ($apps as $details): ?>
<div id="main">
<ul>
<?php echo "<li>App Name: ".$details['app_name'] ?>
<?php echo "<li>EPRID: ".$details['EPRID'] ?>
<?php echo "<li>Requestor: ".$details['requestor'] ?>
<?php echo "<li>Team PDL: ".$details['PDL'] ?>
<?php foreach ($mappings as $map): ?>
<?php echo "<li>ProxyPass /".$map['resource']."/ ".$map['destURL'] ?>
<?php echo "<li>ProxyPassReverse /".$map['resource']."/ ".$map['destURL'] ?>
<?php endforeach ?>
</ul>
</div>
<hr />
<?php endforeach ?>
?>
Getting down to my confusion.... Should I be doing all the foreach looping in the model and/or the controller classes if I'm not going to setup the DataMapper Class?
Is there a way to call the get_prpMappings($id) function defined in the model class directly in the view? The only way for that function to work for me, is when the id of the app row is provided when iterating through the rows.
I tried putting $this->prp_model->get_prpMappings($id); in the view, but the view page doesn't seem to identify the class.
Lastly.. By the looks of it, it appears I would be doing more coding with a framework (such as CodeIgniter or Zend), then it would be to just write everything from scratch. But I'm under the impression the framework is to provide convenience down the road of additional coding. I'm just not seeing it. Please help.
UPDATED! I hope I understand this.
I have modified my logic to express the output desired. Would you be able to tell me if it is an inefficient way? Here is the logic:
MODEL CLASS:
<?php
class Prp_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
//GET APP THE ROWs FROM THE sharedITG TABLE
public function get_appsUsingPrp()
{
$query = $this->db->get('sharedITG');
return $query->result_array();
}
//GET THE MAPPINGS FROM THE sharedITG_mappings TABLE
//FOR EACH APP BY WAY OF UNIQUE id IN THE shareITG TABLE
public function get_prpMappings($id = FALSE)
{
$this->db->select('resourceID, resource, destURL');
$query = $this->db->get_where('sharedITG_mappings', array('resourceID' => $id));
return $query->result_array();
}
public function get_prp()
{
//loop through all apps
foreach ($this->get_appsUsingPrp() as $app)
{
//print_r($app);
foreach ($this->get_prpMappings($app['id']) as $mappings)
{
$map[] = $mappings;
}
}
return $map;
}
}
Controller Class
<?php
class Prp extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('prp_model');
}
public function index()
{
$data['mappings'] = $this->prp_model->get_prp();
$data['apps'] = $this->prp_model->get_appsUsingPrp();
$data['title'] = 'PRP archive';
$this->load->view('templates/header', $data);
$this->load->view('prp/index', $data);
$this->load->view('templates/footer');
}
public function view($id)
{
$data['apps'] = $this->prp_model->get_appsUsingPrp();
$data['mappings'] = $this->prp_model->get_prp();
}
}
VIEW code:
<?php
//print_r($apps);
//print_r($mappings);
foreach ($apps as $details): ?>
<div id="main">
<ul>
<?php echo "<li>App Name: ".$details['app_name'] ?>
<?php echo "<li>EPRID: ".$details['EPRID'] ?>
<?php echo "<li>Requestor: ".$details['requestor'] ?>
<?php echo "<li>Team PDL: ".$details['PDL'] ?>
<?php
foreach ($mappings as $map)
{
if ($details['id'] == $map['resourceID'])
{
echo "<li>ProxyPass /".$map['resource']."/ ".$map['destURL'];
echo "<li>ProxyPassReverse /".$map['resource']."/ ".$map['destURL'];
}
}
?>
</ul>
</div>
<hr />
<?php endforeach ?>
So after further research, I found a forum that gave me a pretty decent example. I'm not sure if its the most optimal way to do this, but it worked for me and still (kind of) maintained the MVC model for Code igniter. The foreach in the function below is what I added. It appears it loops through the current result and obtains all rows for the second table that has a relationship between Table2ID and IDFromTable. Then adds the results by way of $result{$key}.
public function get_resuts()
{
$query = $this->db->get('table1');
$result = $query->result_array();
foreach ( $result as $key => $row )
{
$query = $this->db->get_where('Table2', array('Table2ID' => $row['IDFromTable']));
$row['DesiredFieldFromTable#'] = $query->result_array();
$result[$key] = $row;
}
return $result;
}
Then its available in the view by looping through the second array with the content from the foreach results in the get_resuts() function. I'm interested in learning of other ways to do this too.

Query is returning empty arrays in CakePHP (model and controller are set up)

I'm using Cake's find('all') method in the controller to query a table I have, and the requestAction method to use the controller function (and so to output the data) within the view. The problem is that the find method is returning empty arrays(ouput is 'ArrayArrayArray'). The table is named 'users' (as per Cake conventions) and the code for all three files are below:
Code for the view (test.ctp)
<?php
$users = $this->requestAction('/users/read');
foreach($users as $user) {
echo $user;
}
?>
Code for the controller (users_controller.php)
<?php
class UsersController extends AppController {
var $name = 'Users';
function read(){
$users = $this->User->find('all');
if(isset($this->params['requested'])) {
return $users;
}
}
}
?>
Code for the model (user.php)
<?php
class User extends AppModel {
var $name = 'User';
}
?>
I've dwindled it down and discovered that $users is being set to NULL by the $this->User->find('all') statement because that statement is actually not returning any values. I know Cake is finding the table because of a typo I had earlier with the table name ('usres' instead of 'users'). I can't figure out what I'm missing or what I'm doing wrong. Would love some help. :)
The ouput is 'ArrayArrayArray' doen't means itz empty
try
foreach($users as $user) {
debug($user);
}
For me this code is meaningless.
if you want to use requestAction() use it in the proper way. It's used to call (and print) the parts of the application in the view.
Here is how to achieve the working and correct code:
Your Users class:
class Users extends AppController {
function read(){
$this->set('users', $this->User->find('all'));
$this->layout = "ajax";
$this->render();
}
}
Your read.ctp:
<ul><?php
if(isset($users)){
foreach($users as $user) {
echo '<li>'.$user.'</li>';
}
}
?></ul>
Now in your test.ctp you need to call:
<?php echo $this->requestAction(
array(
'controller'=>'users',
'action'=>'read'
)
);?>
And you will see the result in your test action as unsorted list.