How do you create a settings function in codeigniter? - php

I have created a MY_Controller and I'm linking to it through my main controller... I am now trying to create a settings function which will get all the results from a database and return the one you want... The only problem I'm having is being able to do using the template engine...
protected function settings()
{
// select all settings from database
$query = $this->db->query('SELECT * FROM settings');
// get result from database
$this->data['settings'] = $query->result_array();
// return array of data
return $this->data['settings'];
}
How can i go about this?
The only way I can access it at the moment is:
{settings}
{name}
{value}
{/settings}
P.S. I call the function $this->settings() in the __construct() function also I forgot to mention I'm using codeigniter

Controller code:
$data['settings'] = $this->settings();
$this->load->view('whatever_your_view_file_is_named', $data);
Now in your view the setting properties will be available as members of an object named settings as that was the key you set in the data array you pass to the view.
View code:
echo $settings->name;

Related

Laravel dynamic queries on array of Eloquent models

I am currently trying to make a function that calls different scopeQueries such as scopeByLocation() or scopeByPublished() on models defined in an array. I've got the basics working through [this link][1]. However, when trying to access custom made query scopes that are defined in the corresponding model, I get the following error: "Call to undefined method Illuminate\Database\Query\Builder::ForLocation($location)->get()".
What I want to achieve is a single method which loops through every model in the array of models and retrieves & calls the right scopeQuery on the model, something like this:
$modelElements = $model::{$queryScope}();
Where for example $model = 'Modules\News\Models\Article'
And $queryScope is a defined queryScope in the model itself. E.g. scopeForLocation($location).
I've tested $queryScope = 'all' and I get a result just fine, however when I try to access a custom queryScope ($queryScope = 'ForLocation($location)->get') that exists within for example the Location model, I get the following error: "Call to undefined method Illuminate\Database\Query\Builder::ForLocation($location)->get()".
So this all happens in a foreach-loop where every model in my models-array gets called and then the corresponding queryScope gets called on the model.
Why does the $queryScope = 'all' method works on my dynamic models, but other scopes throw an error? I really hope someone could help me get into the right direction with this issue.
Thanks in advance,
J. Doe.
Okay, I've finally solved it the following way:
//array of models
public function models()
{
return [
'Modules\Website\Models\Article',
...
];
}
//function that retrieves all elements for a model
public function getAllElementsForModel($model, $param)
{
//instantiate model
$model = new $model;
//call queryScope
//'queryScope' could be any queryScope that is defined within your model(s),
//the parameters are needed for the associated queryScope
$query = call_user_func_array([$model, 'queryScope'], [$param1, $param2]);
$result = $query->get();
//do stuff with your $result
}
//retrieves all
public function all($param)
{
//loop through the array of models
foreach($this->models() as $model){
$this->getAllElementsForModel($model, $param);
//do stuff here...
}
}
Sharing is caring!

MVC: Model View interaction in PHP

I'm currently learning the ropes of the MVC pattern and came across a problem I can't seem
to fix in a way I want and is in line with the MVC pattern.
I have set up the router, controllers and views up successfully.
The only thing I don't really get is the use of the Model. I know it's supposed to
serve the Data to the view, and here it is I have a problem.
I want to pass a function thru my view method, but it executes before it should be.
is there a way
I will try to be as specific as possible about the situation so sorry for the long post.
The controller class is this:
class Controller{
private $tpl_name = 'default';
public function model($model){
require('../admin/model/'.$model.'.model.php');
return new $model();
}
public function view($page_title,$file_paths,$params,$data = []) {
// takes an array with the file paths
$this->content = $file_paths;
$tpl_name = $this->tpl_name;
require_once('templates/'.$tpl_name.'/header.php');
require_once('templates/'.$tpl_name.'/nav.php');
require_once('templates/'.$tpl_name.'/content-top.php');
foreach ($file_paths as $content){
require_once('view/'.$content);
}
require_once('templates/'.$tpl_name.'/content-bottom.php');
require_once('templates/'.$tpl_name.'/footer.php');
}
}
The view renders the template I want, takes parameters from the router and, the data that
needs to be handled in the desired view. So far so good.
I want to serve my posts in my admin panel that displays a table of all the posts in the DB.
I have written a method that fetches the data, and a method that writes the data.
class Post{
......
//other functions above
public function displayPosts(){
// get's all the posts form the data base, returns an object array
$posts = Post::fetchContent('posts',0);
// array get's passes to the write function which will write out the data.
$writer = Post::write($posts);
}
static public function write(Array $posts){
foreach($posts as $single){
// for each object in the array, assign the vars so the view can handle them
// to create a single row in the table for each object:
$trashed = $single->getTrashed();
$id = $single->getID();
$title = $single->getTitle();
$category = $single->getCategory();
$content = $single->getContent();
$author = $single->getAuthor();
$date = $single->getDate();
$approved = $single->getApproved();
$dbt = $single->getDbt();
// This is a template which represents a table row with the post data I need.
require('view/content_table.php');
}
//controller file (needs to moved to other file later): handles approve/remove/edit/delete actions.
require('view/manage_content.php');
}
}
Now we have arrived at the problem:
When I call the model in my controller and render the view, it will execute immediatly
before the rest of my view loads, resulting in errors, although it displays the data,
it is not in my template, but above it, just in plain text.
errors:
Notice: Undefined variable: _SESSION in /Volumes/HDD Mac/Websites/server/admin/view/content_table.php on line 8
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at ...)
class Dashboard extends Controller {
public function index($params = null){
$model = $this->model('Post');
$posts = $model->displayPosts();
// view takes: page_title,[array of view files],params from the router,array of data from model
$this->view('Dashboard',['admin.php'],$params,[ 'posts' => $posts]);
}
}
Before I was trying to use MVC I just outputted this in my view:
And it worked just fine.
Non relevant HTML above
$posts = Post::fetchContent('posts',0);
// array get's passes to the write function which will write out the data.
$writer = Post::write($posts);
Non relevant HTML below
But now when I pass the display post function, I just want to do this in my view:
echo $data['posts'];
which doesn't work because it already executed my Write function.
The only way I could work around like this was by adding the content of my write function to the view,
and only pass the fetchContent method to my view method (this will output an array of objects).
But since I need this info in two place I dont want to repeat this code, I would prefer echoing
all out.
Non relevant HTML above
$posts = $data['posts'];
foreach($posts as $single){
// for each object in the array, assign the vars so the view can handle them
// to create a single row in the table for each object:
$trashed = $single->getTrashed();
$id = $single->getID();
$title = $single->getTitle();
$category = $single->getCategory();
$content = $single->getContent();
$author = $single->getAuthor();
$date = $single->getDate();
$approved = $single->getApproved();
$dbt = $single->getDbt();
// This is a template which represents a table row with the post data I need.
require('view/content_table.php');
}
//controller file (needs to moved to other file later): handles approve/remove/edit/delete actions.
require('view/manage_content.php');
Non relevant HTML below
Is it bad practise to just skip the use of the Model here and do it like this:
Non relevant HTML above
$posts = Post::fetchContent('posts',0);
// array get's passes to the write function which will write out the data.
$writer = Post::write($posts);
Non relevant HTML below
Or is there a way to rewrite my Post::Write function? Or just use the foreach loop in the view?
Thank you all for taking the time!
If you need more info, just ask:-)

Fetch data from database issue

i have one issue i make a component and i add data add component data table that i want to fetch that data in my site how to do and i have one other issue how to put query in view.html.php file in components i have code i add my code i have one error i add my error
500 - View class not found [class, file]: team_memberViewteam_member, C:\wamp\www\Joomla_2.5.8-Stable-Full_Package\components\com_team_member\views\team_member\view.html.php
this is my code please help me how to fetch data in database....
// import Joomla view library
jimport('joomla.application.component.view');
/**
* HTML View class for the HelloWorld Component
*/
class HelloWorldViewHelloWorld extends JView
{
// Overwriting JView display method
function display($tpl = null)
{
// Assign data to the view
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select(array('id', 'member_name', 'member_pic', 'member_des','member_description'));
$query->from('#__gztqw_team_member_datadetails');
$query->where('profile_key LIKE \'custom.%\'');
$query->order('ordering ASC');
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects.
$results = $db->loadObjectList();
// Display the view
parent::display($tpl);
}
}
try simple way:-
$db = JFactory::getDbo();
$query = 'SELECT data FROM #__gztqw_team_member_datadetails WHERE profile_key LIKE "custom.%" order by ASC';
$db->setQuery($query);
$results = $db->loadObjectList();
also you have not returened any value in function and where you have display it the best way to show data in view use controllers function and assign result value to display in view
you need to read http://docs.joomla.org/Developing_a_Model-View-Controller_%28MVC%29_Component_for_Joomla!2.5
First of all, the class in your view is called HelloWorldViewHelloWorld, it should be called Team_memberViewTeam_member, this is what is causing your error.
Secondly, You should ideally put your database query into your model, however it will still work if you put it in your view. I have given you an example of how to make it work with the query in the view.
I have created a protected variable called $items, and assigned the results from the database to the variable.
In your template, you would then access the data from the database using
foreach($this->items as $item):
echo $item->id;
endforeach();
In your view you should have
class Team_memberViewTeam_member extends JView
{
protected $items;
// Overwriting JView display method
public function display($tpl = null)
{
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select(array('id', 'member_name', 'member_pic','member_des','member_description'));
$query->from('#__gztqw_team_member_datadetails');
$query->where('profile_key LIKE \'custom.%\'');
$query->order('ordering ASC');
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects.
$this->items = $db->loadObjectList();
parent::display($tpl);
}
}

Magento Controller shows all the rows from table

As I am required to pirnt the ratings of products in JSON format, i have made a module with controller and rating.php file in model folder. We I run the controller it shows all the data from that table, But I required only a single row. So through the url i am passing a parameter, but it wont works. I am attaching my indexcontroller.php here. suggest me upon this.
<?php
class Modulename_CustomRating_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction ()
{
$arrParams = $this->getRequest()->getParams();
var_dump($arrParams);
$collection = Mage::getModel('Modulename_CustomRating_Model_CustomRating')->getCollection();
}
print_r (json_encode($collection ->getData()));
}
}
?>
As I am passing url as:localhost/magento/customrating?vote_id=1 , it is taking the parameter to it but returns whole table's data. I know this is due to getData(); but how to make to get the required row?
You have to use setEntityPkFilter method. Check Mage_Rating_Model_Resource_Rating_Option_Vote_Collection class for other methods.
$product_id = $this->getRequest()->getParam('product_id'); // or 'vote_id'
$collection = Mage::getModel('Modulename_CustomRating_Model_CustomRating')
->getResourceCollection()
->setEntityPkFilter($product_id);
If you want only 1 column you can try some Zend stuff because you can't use addAttributeToSelect. getSelect() returns Zend like query:
$adapter = $this->getConnection(); // $this->getConnection();
$collection->getSelect()
->reset(Zend_Db_Select::COLUMNS) // remove all columns
->columns('attribute_name'); // add only needed one
$result = $adapter->fetchAll($select);
Not sure whether this would work. It's not tested, just an idea.

how to echo out data using findAllBySql in active record

This should return a list of about five locations. It returns nothing with no errors. I've tested the sql using mysql workbench. It returns the data just fine. Right now I'm writing the back end so I'm not concerned with using views or the dataprovider. I'm just making sure my back end functions work. So with that in mind, how would you return the data retrieved by findAllBySql?
class CashLogic
{
public function AllLocations()
{
$model = new Locations;
$allLocations = $model->findAllBySql("SELECT name from locations");
return $allLocations;
}
}
class SiteController extends Controller
{
public function actionIndex()
{
$model = new CashLogic;
$data = $model->AllLocations();
return $data;
}
}
The findAllBySql() method returns an array of models. From your code it seems you only want the names of locations. An alternative method is
$AllLocations=CHtml::listData(Locations::model()->findAll(),'name','name');
This will return an array of the form array('name'=>'name','name'=>'name'). A better solution would be to replace the first name with the primary key of your locations table.

Categories