How can i load model in joomla? - module

This is my Controller
// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.application.component.controller');
/**
* Hello World Component Controller
*
* #package Joomla.Tutorials
* #subpackage Components
*/
class HelloController extends JController
{
/**
* Method to display the view
*
* #access public
*/
function __construct($default = array())
{
parent::__construct($default);
// Register Extra tasks
$this->registerTask( 'detail' , 'display' );
}
function display()
{
switch($this->getTask())
{
case 'detail' :
{
JRequest::setVar( 'view' , 'new');
// Checkout the weblink
$model = $this->getModel('hello');
} break;
}
parent::display();
}
}
this is my view.html.php
class HelloViewNew extends JView
{
function display($tpl = null)
{
global $mainframe;
$db =& JFactory::getDBO();
$model =& $this->getModel('hello');
$items = & $model->getdetail();
$this->assignRef( 'items', $items );
parent::display($tpl);
}
}
and this is my model
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.application.component.model' );
/**
* Hello Model
*
* #package Joomla.Tutorials
* #subpackage Components
*/
class HelloModelHello extends JModel
{
/**
* Gets the greeting
* #return string The greeting to be displayed to the user
*/
var $_data;
/**
* Returns the query
* #return string The query to be used to retrieve the rows from the database
*/
function _buildQuery()
{
$query = ' SELECT * '
. ' FROM #__hello WHERE published = 1'
;
return $query;
}
/**
* Retrieves the hello data
* #return array Array of objects containing the data from the database
*/
function getData()
{
// Lets load the data if it doesn't already exist
if (empty( $this->_data ))
{
$query = $this->_buildQuery();
$this->_data = $this->_getList( $query );
}
//echo "<pre>"; print_r($this->_data); exit;
return $this->_data;
}
function detail()
{
echo "this is test"; exit;
}
}
My question is how can i fetch that detail function from database its not working for me?

on your model, you've the function : function detail() ,
But you've tried to call the function on view with : $items = & $model->getdetail();
Remember your function is detail() NOT getdetail() . So, call with :
$items = & $model->detail();
That's your only mistake I guess so, good luck

you should use this in contoller
$view = $this->getView();
$view->setModel($this->getModel());
then you can use $this->getModel() in view.

Related

Prestashop 1.7 - City field as dropdown or autocomplete

I am using Prestashop 1.7 and I need to change the city input field.
I have a billing software that only allows me to use predefined cities. So I have created a table ps_cities with the entries (id an city name).
I know how to write a dropdown or a autocomplete script, but I do not know where to change the input type in the Prestashop files.
On the 1.6 version you have the input field in a theme file, but somehow I fail to find in the new version.
In PrestaShop 1.7.7.X I've created a module that includes some new (and cool!) hooks like showing below. I consider this one a good option because it will be easier to maintain in the next PrestaShop releases.
Some assumptions here: I created a relationship model CityAddress with two fields id_city and id_address and a City model with fields like name, id_state, id_country, also I continued using Address::city string name for compatibility.
/**
* #see /classes/form/CustomerAddressFormatter.php#L156
* #param array $param [
* #var array $fields
* ]
*/
public function hookAdditionalCustomerAddressFields($params)
{
($params['fields']['city'])->setType('hidden');
// New field
$formField = $params['fields'];
$formField = (new FormField())
->setName('id_city')
->setLabel($this->l('City'))
->setRequired(true)
->setType('select')
;
// If an address already exits, select the default city
if (Tools::getIsset('id_address')) {
$address = new Address(Tools::getValue('id_address'));
if (!empty($address->id_state)) {
$cities = City::getCitiesByIdState((int) $address->id_state);
if (!empty($cities)) {
foreach ($cities as $city) {
$formField->addAvailableValue(
$city['id_city'],
$city['name']
);
}
$id_city = CityAddress::getIdCityByIdAddress((int) $address->id);
$formField->setValue($id_city);
}
}
}
// Add the id_city field in the position of the city field
$keys = array_keys($params['fields']);
$search = 'city';
foreach ($keys as $key => $value) {
if ($value == $search) {
break;
}
}
$part1 = array_slice($params['fields'], 0, $key + 1);
$part2 = array_slice($params['fields'], $key + 1);
$part1['id_city'] = $formField;
$params['fields'] = array_merge($part1, $part2);
}
This one to validate the field:
/**
* #see /classes/form/CustomerAddressForm.php#L123
* #param array $param [
* #var CustomerAddressForm $form
* ]
*/
public function hookActionValidateCustomerAddressForm($params)
{
if (empty(Tools::getValue('id_city'))
|| empty(Tools::getValue('city'))) {
return false;
}
$form = $params['form'];
$idCityField = $form->getField('id_city');
$idCity = (int) Tools::getValue('id_city');
$cityObj = new City($idCity);
$city = pSQL(Tools::getValue('city'));
if ($cityObj->name !== $city) {
$idCityField->addError(sprintf(
$this->l('Invalid name in field id_city %s and city %s'),
$cityObj->name,
$city
));
return false;
}
return true;
}
And the submitted field:
/**
* #see /classes/form/CustomerAddressForm.php#L153
* #param array $param [
* #var Address $address
* ]
*/
public function hookActionSubmitCustomerAddressForm($params)
{
/** #var Address */
$address = $params['address'];
$address->save();
if (!Validate::isLoadedObject($address)) {
throw new PrestaShopException($this->l('Address object error while trying to save city'));
}
// If address has a previous value then update it
$cityAddress = CityAddress::getCityAddressByIdAddress((int) $address->id);
$city = City::getCityByNameAndIdState($address->city, $address->id_state);
$cityAddress->id_city = $city->id;
$cityAddress->id_address = $address->id;
$cityAddress->save();
}
It is possible if you have this line in the additionalCustomerAddressFields hook:
https://github.com/PrestaShop/PrestaShop/blob/develop/classes/form/CustomerAddressFormatter.php#L150
For previous version I included ['fields' => &$format] as a parameter.
You can find all form fields of the Front Office in your theme's /templates/_partials/form-fields.tpl file

TYPO3 9 get resources and categories from pages, queryBuilder join problems

This solution was working til TYPO3 8.7. But breaks in TYPO3 9.
I've some submenu showing images from page-resources and using categories.descriptions for css.
I use custom viewhelpers for that. But now the JOIN-sql is broken... Don't know why, because it worked in 8.7 and previous.
<?php
namespace EnzephaloN\ThemePsoa\ViewHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
class SysCategoryViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {
/**
* #var integer $uid (CE)
*/
public function initializeArguments() {
$this->registerArgument('uid', 'integer', 'enthaelt die UID des CE', TRUE);
}
/**
* #var integer $uid
*/
public function render($uid = null) {
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_category');
$queryBuilder->getRestrictions()
->removeAll();
$query = $queryBuilder
->select('*')
->from('sys_category')
->join('sys_category','sys_category_record_mm','MM', $queryBuilder->expr()->andX($queryBuilder->expr()->eq('MM.uid_foreign', $uid),$queryBuilder->expr()->eq('MM.uid_local', 'uid')))
->setMaxResults(1);
$result = $query->execute();
$res = [];
while ($row = $result->fetch()) {
$res[] = $row;
}
$this->templateVariableContainer->add('sysCategoryDetailArray', $res);
}
}
ERRORMESSAGE
(1/2) Doctrine\DBAL\Exception\SyntaxErrorException
An exception occurred while executing
SELECT * FROM sys_category INNER JOIN sys_category_record_mm MM ON
(`MM`.`uid_foreign` = ) AND (MM.uid_local = uid)
LIMIT 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AND (MM.uid_local = uid) LIMIT 1' at line 1
and for fal:
<?php
namespace EnzephaloN\ThemePsoa\ViewHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
class FalResourceViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {
/**
* #author INGENIUMDESIGN
*/
public function initializeArguments() {
$this->registerArgument('uid', 'integer', 'enthaelt die UID des CE', TRUE);
}
/**
* #var mixed $uid
*/
public function render($uid = null) {
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file');
if($uid) {
$query = $queryBuilder
->select('*')
->from('sys_file')
->join('sys_file', 'sys_file_reference', 'MM',
$queryBuilder->expr()->andX(
$queryBuilder->expr()->andX(
$queryBuilder->expr()->eq('MM.uid_foreign', $uid),
$queryBuilder->expr()->eq('MM.tablenames', '"pages"')
),
$queryBuilder->expr()->eq('MM.uid_local', 'sys_file.uid')
)
)
->setMaxResults(1);
//die($query->getSQL());
$result = $query->execute();
$res = [];
while ($row = $result->fetch()) {
$res[] = $row;
}
$this->templateVariableContainer->add('sysFileArray', $res);
}
}
}
Can anybody check those queryBuilder-statements?
Thanx in advance
EnzephaloN
Here's the solution:
FalResourceViewhelper
Just use the TYPO3-core-method $fileRepository->findByRelation(); This returns the page-related resources.
Use like this:
<e:falResource data="{page.data}" table="pages" field="media" as="sysFileArray">
<f:if condition="{sysFileArray.0.uid}!=0">
<f:image src="{sysFileArray.0.uid}" treatIdAsReference="1" class="img-responsive"/>
</f:if>
</e:falResouce>
<?php
namespace EnzephaloN\ThemePsoa\ViewHelper;
use TYPO3\CMS\Core\Resource\FileRepository;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
/**
* FalViewHelper
*/
class FalResourceViewHelper extends AbstractViewHelper{
use CompileWithRenderStatic;
/**
* #var bool
*/
protected $escapeOutput = false;
/**
* Initialize arguments.
*
* #throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception
*/
public function initializeArguments()
{
parent::initializeArguments();
$this->registerArgument('data', 'array', 'Data of current record', true);
$this->registerArgument('table', 'string', 'table', false, 'tt_content');
$this->registerArgument('field', 'string', 'field', false, 'image');
$this->registerArgument('as', 'string', 'Name of variable to create', false, 'items');
}
/**
* #param array $arguments
* #param \Closure $renderChildrenClosure
* #param RenderingContextInterface $renderingContext
* #return string
*/
public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext) {
$variableProvider = $renderingContext->getVariableProvider();
if (is_array($arguments['data']) && $arguments['data']['uid'] && $arguments['data'][$arguments['field']]) {
$fileRepository = GeneralUtility::makeInstance(FileRepository::class);
$items = $fileRepository->findByRelation(
$arguments['table'],
$arguments['field'],
$arguments['data']['uid']
);
$localizedId = null;
if (isset($arguments['data']['_LOCALIZED_UID'])) {
$localizedId = $arguments['data']['_LOCALIZED_UID'];
} elseif (isset($arguments['data']['_PAGES_OVERLAY_UID'])) {
$localizedId = $arguments['data']['_PAGES_OVERLAY_UID'];
}
$isTableLocalizable = (
!empty($GLOBALS['TCA'][$arguments['table']]['ctrl']['languageField'])
&& !empty($GLOBALS['TCA'][$arguments['table']]['ctrl']['transOrigPointerField'])
);
if ($isTableLocalizable && $localizedId !== null) {
$items = $fileRepository->findByRelation($arguments['table'], $arguments['field'], $localizedId);
}
} else {
$items = null;
}
$variableProvider->add($arguments['as'], $items);
$content = $renderChildrenClosure();
$variableProvider->remove($arguments['as']);
return $content;
}
}
It's easy.
--
SysCategoryViewHelper works like this:
<e:sysCategory data="{page.data}" as="sysCategoryDetailArray">
<f:if condition="{sysCategoryDetailArray.0}">
<i class="fa fa-4x {sysCategoryDetailArray.0.description}"></i>
</f:if>
</e:sysCategory>
And here is the code:
<?php
namespace EnzephaloN\ThemePsoa\ViewHelper;
use TYPO3\CMS\Core\Resource\FileRepository;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
use TYPO3\CMS\Core\Database\ConnectionPool;
class SysCategoryViewHelper extends \TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper {
use CompileWithRenderStatic;
/**
* #var bool
*/
protected $escapeOutput = false;
/**
* Initialize arguments.
*
* #throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception
*/
public function initializeArguments()
{
parent::initializeArguments();
$this->registerArgument('data', 'array', 'Data of current record', true);
$this->registerArgument('as', 'string', 'Name of variable to create', false, 'items');
}
/**
* #param array $arguments
* #param \Closure $renderChildrenClosure
* #param RenderingContextInterface $renderingContext
* #return string
*/
public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext) {
$variableProvider = $renderingContext->getVariableProvider();
if (is_array($arguments['data']) && $arguments['data']['uid']) {
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_category');
$queryBuilder->getRestrictions()
->removeAll();
$query = $queryBuilder
->select('*')
->from('sys_category')
->join('sys_category', 'sys_category_record_mm', 'MM', $queryBuilder->expr()->andX(
$queryBuilder->expr()->eq('MM.uid_foreign', $arguments['data']['uid']),
$queryBuilder->expr()->eq('MM.uid_local','sys_category.uid')));
$result = $query->execute();
$items = [];
while ($row = $result->fetch()) {
$items[] = $row;
}
} else {
$items = null;
}
$variableProvider->add($arguments['as'], $items);
$content = $renderChildrenClosure();
$variableProvider->remove($arguments['as']);
return $content;
}
}

DI container can't find a class

I have an existing application with line below
\Yii::$container->invoke([$this, 'injections']);
and this line couses the error
ReflectionException Class Redis does not exist
I have a file Redis.php where defined class Redis in the /common/components directory.
But yii looks for it at the /common/components/myAPI/
А class that contains a line
\Yii::$container->invoke([$this, 'injections']);
ia located by the path /common/components/myAPI/
The whole class where I try to call the Redis
abstract class AEntity{
const API_BE_SOCCER_COUNTER = 'API_BE_SOCCER_COUNTER';
/**
* #var Fetcher $_fetcher
* #var boolean $_isFromCache
* #var APIConfig $_config
* #var string $_redisKey
* #var array $_params
*/
private $_fetcher,
$_isFromCache = null,
$_params = [],
$_redisKey = null,
$_mainApi;
/**
* #var APIRedisManager $_redis
*/
private $_redis,
$_config;
/**
* #var Array $_dbTable
* #var Array $_dbMap
*/
protected $_dbMap,
$_dbTable;
/**
*
* #return array
*/
protected function setParams(Array $params = []){
$this->_params = $params;
}
protected abstract function keyRelationShip();
protected abstract function getAttributes();
protected abstract function jsonArrayMap();
protected function setRedisKey($redisData){
$this->_redisKey = $redisData;
}
protected function mapArrays(){
$jsonArrayMap = $this->jsonArrayMap();
foreach ($jsonArrayMap as $arrayMap){
$mapPath = $arrayMap['path'] ? explode('.', $arrayMap['path']) : null;
$key = $arrayMap['key'];
$arr = $arrayMap['array'];
$assoc = $arrayMap['assoc'];
$tmpData = $this->_mainApi;
if($mapPath){
foreach($mapPath as $mapper) {
if(!isset($tmpData[$mapper])){
$this->{$key} = null;
return false;
}
$tmpData = $tmpData[$mapper];
}
}
$this->{$key} = $arr ? $this->jsonArrayMapper($tmpData, $assoc, $mapPath) : $tmpData;
}
}
public function injections(APIConfig $config, Fetcher $fetcher, APIRedisManager $redisManager){
$this->_config = $config;
$this->_fetcher = $fetcher;
$this->_redis = $redisManager;
}
protected function initialize(Array $params = []){
$constant = static::keyRelationShip();
$redisKey = $this->paramToRedis($params);
$this->setParams($params);
$this->setRedisKey($redisKey);
\Yii::$container->invoke([$this, 'injections']);
$this->_config->get($constant, $this->_params);
$this->_redis->setConfig($this->_config);
$this->_fetcher->setConfig($this->_config);
$this->_mainApi = $this->getAPIRequest();
$this->mapArrays();
}
/**
* #return array
*/
public function getMainApi(){
return $this->_mainApi;
}
/**
* #return APIRedisManager
*/
public function getRedis(){
return $this->_redis;
}
/**
* #return array
* #throws \Exception
*/
public function loadYiiData(){
$arrModel = [];
if (!$this->_dbTable) new Exception('No Table Specified.');
if (!$this->_dbMap) new Exception('No DB Map Specified.');
foreach ($this->_dbMap as $keyApi => $keyDB){
if(!isset($this->$keyDB)) throw new \Exception("KeyDB: $keyDB, is not Set");
$arrModel[$this->_dbTable][$keyApi] = $this->$keyDB;
}
return $arrModel;
}
/**
* GET API request logic
*
* #return array
*/
public function getAPIRequest(){
$redisKey = $this->formulateRedisKeyLogic();
$storedRequest = $this->_redis->getConfig() ? $this->_redis->get($redisKey) : null;
if(!$storedRequest){
$this->_isFromCache = false;
$apiRequestResult = $this->_fetcher->get()->asArray();
$this->_redis->incrCounter();
if($apiRequestResult && !$storedRequest){
$serializedApiRequest = serialize($apiRequestResult);
$this->_redis->store($serializedApiRequest, $redisKey);
}
}else{
$this->_isFromCache = true;
$apiRequestResult = unserialize($storedRequest);
}
return $apiRequestResult;
}
/** #return boolean */
public function isFromCache(){
return $this->_isFromCache;
}
private function formulateRedisKeyLogic(){
$config = $this->_redis->getConfig();
if(isset($config['key']) && strpos($this->_redisKey,'$.')!==false){
$configKey = $config['key'];
$redisKey = $configKey . $this->_redisKey;
$redisKey = str_replace('$.', '', $redisKey);
}
else{
$redisKey = $this->_redisKey;
}
return $redisKey;
}
protected function paramToRedis($param){
$className = (new \ReflectionClass($this))->getShortName();
$buildRedisKey = '$._'.str_replace('=', '_', http_build_query($param, null, ','));
$paramKey = $buildRedisKey.'_'.$className;
return $paramKey;
}
/**
* GET API request logic
*
* #return array
*/
protected function jsonArrayMapper(Array $entityItems, $assoc = false, $mapPath= true){
$aEntityArray = [];
$attributes = $this->getAttributes();
$Klass = static::class;
if($mapPath){
foreach ($entityItems as $entityItem){
$aEntity = new $Klass(false);
foreach ($attributes as $attribute){
$aEntity->{$attribute} = $entityItem[$attribute];
}
$assoc ? $aEntityArray[$entityItem[$assoc]] = $aEntity : $aEntityArray[] = $aEntity;
}
}else{
$aEntity = new $Klass(false);
foreach ($attributes as $attribute){
$aEntity->{$attribute} = $entityItems[$attribute];
}
$aEntityArray = $aEntity;
}
return $aEntityArray;
}
public function __set($key, $value){
$this->{$key} = $value;
}
public function __get($name) {
return $this->{$key};
}
}
This is a super class for class those have such constructor
public function __construct($fullInitizalization=true, $params = []) {
if($fullInitizalization){
$redisParams = $this->paramToRedis($params);
parent::initialize($params);
}
}
When DI container trying to instaniate APIRedisConnection class, it passes parameter with type Redis:
/** #param Redis $redis */
function __construct(Redis $redis){
$this->_redis = $redis;
}
Class Redis can't be found in the project, but I can see it in IDE and this class was written on PHP 7
Although the whole project written on PHP 5.6

Google map API code

Hi I am trying to get my Google maps to show up on my Joomla site but it is not working. I keep getting the following error message:
Oops! Something went wrong. This page didn't load Google Maps
correctly. See the JavaScript console for technical details.
Here is the code that I currently have:
<?php
/**
* #package Joomla.Platform
* #subpackage Google
*
* #copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved
* #license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
use Joomla\Registry\Registry;
/**
* Google Maps embed class for the Joomla Platform.
*
* #since 12.3
*/
class JGoogleEmbedMaps extends JGoogleEmbed
{
/**
* #var JHttp The HTTP client object to use in sending HTTP requests.
* #since 12.3
*/
protected $http;
/**
* Constructor.
*
* #param Registry $options Google options object
* #param JUri $uri URL of the page being rendered
* #param JHttp $http Http client for geocoding requests
*
* #since 12.3
*/
public function __construct(Registry $options = null, JUri $uri = null, JHttp $http = null)
{
parent::__construct($options, $uri);
$this->http = $http ? $http : new JHttp($this->options);
}
/**
* Method to get the API key
*
* #return string The Google Maps API key
*
* #since 12.3
*/
public function getKey()
{
return $this->getOption('key');
}
/**
* Method to set the API key
*
* #param string $key The Google Maps API key
*
* #return JGoogleEmbedMaps The object for method chaining
*
* #since 12.3
*/
public function setKey($key)
{
$this->setOption('key', $key);
return $this;
}
/**
* Method to get the id of the map div
*
* #return string The ID
*
* #since 12.3
*/
public function getMapId()
{
return $this->getOption('mapid') ? $this->getOption('mapid') : 'map_canvas';
}
/**
* Method to set the map div id
*
* #param string $id The ID
*
* #return JGoogleEmbedMaps The object for method chaining
*
* #since 12.3
*/
public function setMapId($id)
{
$this->setOption('mapid', $id);
return $this;
}
/**
* Method to get the class of the map div
*
* #return string The class
*
* #since 12.3
*/
public function getMapClass()
{
return $this->getOption('mapclass') ? $this->getOption('mapclass') : '';
}
/**
* Method to set the map div class
*
* #param string $class The class
*
* #return JGoogleEmbedMaps The object for method chaining
*
* #since 12.3
*/
public function setMapClass($class)
{
$this->setOption('mapclass', $class);
return $this;
}
/**
* Method to get the style of the map div
*
* #return string The style
*
* #since 12.3
*/
public function getMapStyle()
{
return $this->getOption('mapstyle') ? $this->getOption('mapstyle') : '';
}
/**
* Method to set the map div style
*
* #param string $style The style
*
* #return JGoogleEmbedMaps The object for method chaining
*
* #since 12.3
*/
public function setMapStyle($style)
{
$this->setOption('mapstyle', $style);
return $this;
}
/**
* Method to get the map type setting
*
* #return string The class
*
* #since 12.3
*/
public function getMapType()
{
return $this->getOption('maptype') ? $this->getOption('maptype') : 'ROADMAP';
}
/**
* Method to set the map type ()
*
* #param string $type Valid types are ROADMAP, SATELLITE, HYBRID, and TERRAIN
*
* #return JGoogleEmbedMaps The object for method chaining
*
* #since 12.3
*/
public function setMapType($type)
{
$this->setOption('maptype', strtoupper($type));
return $this;
}
/**
* Method to get additional map options
*
* #return string The options
*
* #since 12.3
*/
public function getAdditionalMapOptions()
{
return $this->getOption('mapoptions') ? $this->getOption('mapoptions') : array();
}
/**
* Method to add additional map options
*
* #param array $options Additional map options
*
* #return JGoogleEmbedMaps The object for method chaining
*
* #since 12.3
*/
public function setAdditionalMapOptions($options)
{
$this->setOption('mapoptions', $options);
return $this;
}
/**
* Method to get additional map options
*
* #return string The options
*
* #since 12.3
*/
public function getAdditionalJavascript()
{
return $this->getOption('extrascript') ? $this->getOption('extrascript') : '';
}
/**
* Method to add additional javascript
*
* #param array $script Additional javascript
*
* #return JGoogleEmbedMaps The object for method chaining
*
* #since 12.3
*/
public function setAdditionalJavascript($script)
{
$this->setOption('extrascript', $script);
return $this;
}
/**
* Method to get the zoom
*
* #return int The zoom level
*
* #since 12.3
*/
public function getZoom()
{
return $this->getOption('zoom') ? $this->getOption('zoom') : 0;
}
/**
* Method to set the map zoom
*
* #param int $zoom Zoom level (0 is whole world)
*
* #return JGoogleEmbedMaps The object for method chaining
*
* #since 12.3
*/
public function setZoom($zoom)
{
$this->setOption('zoom', $zoom);
return $this;
}
/**
* Method to set the center of the map
*
* #return mixed A latitude longitude array or an address string
*
* #since 12.3
*/
public function getCenter()
{
return $this->getOption('mapcenter') ? $this->getOption('mapcenter') : array(0, 0);
}
/**
* Method to set the center of the map
*
* #param mixed $location A latitude/longitude array or an address string
* #param mixed $title Title of marker or false for no marker
* #param array $markeroptions Options for marker
* #param array $markerevents Events for marker
*
* #example with events call:
* $map->setCenter(
* array(0, 0),
* 'Map Center',
* array(),
* array(
* 'click' => 'function() { // code goes here }
* )
* )
*
* #return JGoogleEmbedMaps The latitude/longitude of the center or false on failure
*
* #since 12.3
*/
public function setCenter($location, $title = true, $markeroptions = array(), $markerevents = array())
{
if ($title)
{
$title = is_string($title) ? $title : null;
if (!$marker = $this->addMarker($location, $title, $markeroptions, $markerevents))
{
return false;
}
$location = $marker['loc'];
}
elseif (is_string($location))
{
$geocode = $this->geocodeAddress($location);
if (!$geocode)
{
return false;
}
$location = $geocode['geometry']['location'];
$location = array_values($location);
}
$this->setOption('mapcenter', $location);
return $this;
}
/**
* Method to add an event handler to the map.
* Event handlers must be passed in either as callback name or fully qualified function declaration
*
* #param string $type The event name
* #param string $function The event handling function body
*
* #example to add an event call:
* $map->addEventHandler('click', 'function(){ alert("map click event"); }');
*
* #return JGoogleEmbedMaps The object for method chaining
*
* #since 12.3
*/
public function addEventHandler($type, $function)
{
$events = $this->listEventHandlers();
$events[$type] = $function;
$this->setOption('events', $events);
return $this;
}
/**
* Method to remove an event handler from the map
*
* #param string $type The event name
*
* #example to delete an event call:
* $map->deleteEventHandler('click');
*
* #return string The event handler content
*
* #since 12.3
*/
public function deleteEventHandler($type = null)
{
$events = $this->listEventHandlers();
if ($type === null || !isset($events[$type]))
{
return;
}
$event = $events[$type];
unset($events[$type]);
$this->setOption('events', $events);
return $event;
}
/**
* List the events added to the map
*
* #return array A list of events
*
* #since 12.3
*/
public function listEventHandlers()
{
return $this->getOption('events') ? $this->getOption('events') : array();
}
/**
* Add a marker to the map
*
* #param mixed $location A latitude/longitude array or an address string
* #param mixed $title The hover-text for the marker
* #param array $options Options for marker
* #param array $events Events for marker
*
* #example with events call:
* $map->addMarker(
* array(0, 0),
* 'My Marker',
* array(),
* array(
* 'click' => 'function() { // code goes here }
* )
* )
*
* #return mixed The marker or false on failure
*
* #since 12.3
*/
public function addMarker($location, $title = null, $options = array(), $events = array())
{
if (is_string($location))
{
if (!$title)
{
$title = $location;
}
$geocode = $this->geocodeAddress($location);
if (!$geocode)
{
return false;
}
$location = $geocode['geometry']['location'];
}
elseif (!$title)
{
$title = implode(', ', $location);
}
$location = array_values($location);
$marker = array('loc' => $location, 'title' => $title, 'options' => $options, 'events' => $events);
$markers = $this->listMarkers();
$markers[] = $marker;
$this->setOption('markers', $markers);
return $marker;
}
/**
* List the markers added to the map
*
* #return array A list of markers
*
* #since 12.3
*/
public function listMarkers()
{
return $this->getOption('markers') ? $this->getOption('markers') : array();
}
/**
* Delete a marker from the map
*
* #param int $index Index of marker to delete (defaults to last added marker)
*
* #return array The latitude/longitude of the deleted marker
*
* #since 12.3
*/
public function deleteMarker($index = null)
{
$markers = $this->listMarkers();
if ($index === null)
{
$index = count($markers) - 1;
}
if ($index >= count($markers) || $index < 0)
{
throw new OutOfBoundsException('Marker index out of bounds.');
}
$marker = $markers[$index];
unset($markers[$index]);
$markers = array_values($markers);
$this->setOption('markers', $markers);
return $marker;
}
/**
* Checks if the javascript is set to be asynchronous
*
* #return boolean True if asynchronous
*
* #since 12.3
*/
public function isAsync()
{
return $this->getOption('async') === null ? true : $this->getOption('async');
}
/**
* Load javascript asynchronously
*
* #return JGoogleEmbedMaps The object for method chaining
*
* #since 12.3
*/
public function useAsync()
{
$this->setOption('async', true);
return $this;
}
/**
* Load javascript synchronously
*
* #return JGoogleEmbedAMaps The object for method chaining
*
* #since 12.3
*/
public function useSync()
{
$this->setOption('async', false);
return $this;
}
/**
* Method to get callback function for async javascript loading
*
* #return string The ID
*
* #since 12.3
*/
public function getAsyncCallback()
{
return $this->getOption('callback') ? $this->getOption('callback') : 'initialize';
}
/**
* Method to set the callback function for async javascript loading
*
* #param string $callback The callback function name
*
* #return JGoogleEmbedMaps The object for method chaining
*
* #since 12.3
*/
public function setAsyncCallback($callback)
{
$this->setOption('callback', $callback);
return $this;
}
/**
* Checks if a sensor is set to be required
*
* #return boolean True if asynchronous
*
* #since 12.3
*/
public function hasSensor()
{
return $this->getOption('sensor') === null ? false : $this->getOption('sensor');
}
/**
* Require access to sensor data
*
* #return JGoogleEmbedMaps The object for method chaining
*
* #since 12.3
*/
public function useSensor()
{
$this->setOption('sensor', true);
return $this;
}
/**
* Don't require access to sensor data
*
* #return JGoogleEmbedAMaps The object for method chaining
*
* #since 12.3
*/
public function noSensor()
{
$this->setOption('sensor', false);
return $this;
}
/**
* Checks how the script should be loaded
*
* #return string Autoload type (onload, jquery, mootools, or false)
*
* #since 12.3
*/
public function getAutoload()
{
return $this->getOption('autoload') ? $this->getOption('autoload') : 'false';
}
/**
* Automatically add the callback to the window
*
* #param string $type The method to add the callback (options are onload, jquery, mootools, and false)
*
* #return JGoogleEmbedAMaps The object for method chaining
*
* #since 12.3
*/
public function setAutoload($type = 'onload')
{
$this->setOption('autoload', $type);
return $this;
}
/**
* Get code to load Google Maps javascript
*
* #return string Javascript code
*
* #since 12.3
*/
public function getHeader()
{
$zoom = $this->getZoom();
$center = $this->getCenter();
$maptype = $this->getMapType();
$id = $this->getMapId();
$scheme = $this->isSecure() ? 'https' : 'http';
$key = $this->getKey();
$sensor = $this->hasSensor() ? 'true' : 'false';
$setup = 'var mapOptions = {';
$setup .= "zoom: {$zoom},";
$setup .= "center: new google.maps.LatLng({$center[0]},{$center[1]}),";
$setup .= "mapTypeId: google.maps.MapTypeId.{$maptype},";
$setup .= substr(json_encode($this->getAdditionalMapOptions()), 1, -1);
$setup .= '};';
$setup .= "var map = new google.maps.Map(document.getElementById('{$id}'), mapOptions);";
$events = $this->listEventHandlers();
if (isset($events) && count($events))
{
foreach ($events as $type => $handler)
{
$setup .= "google.maps.event.addListener(map, '{$type}', {$handler});";
}
}
$markers = $this->listMarkers();
if (isset($markers) && count($markers))
{
$setup .= "var marker;";
foreach ($markers as $marker)
{
$loc = $marker['loc'];
$title = $marker['title'];
$options = $marker['options'];
$setup .= 'marker = new google.maps.Marker({';
$setup .= "position: new google.maps.LatLng({$loc[0]},{$loc[1]}),";
$setup .= 'map: map,';
$setup .= "title:'{$title}',";
$setup .= substr(json_encode($options), 1, -1);
$setup .= '});';
if (isset($marker['events']) && is_array($marker['events']))
{
foreach ($marker['events'] as $type => $handler)
{
$setup .= 'google.maps.event.addListener(marker, "' . $type . '", ' . $handler . ');';
}
}
}
}
$setup .= $this->getAdditionalJavascript();
if ($this->isAsync())
{
$asynccallback = $this->getAsyncCallback();
$output = '<script type="text/javascript">';
$output .= "function {$asynccallback}() {";
$output .= $setup;
$output .= '}';
$onload = "function() {";
$onload .= 'var script = document.createElement("script");';
$onload .= 'script.type = "text/javascript";';
$onload .= "script.src = '{$scheme}://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" : "")
. "sensor={$sensor}&callback={$asynccallback}';";
$onload .= 'document.body.appendChild(script);';
$onload .= '}';
}
else
{
$output = "<script src='https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap'>";
$output .= '</script>';
$output .= '<script type="text/javascript">';
$onload = "function() {";
$onload .= $setup;
$onload .= '}';
}
switch ($this->getAutoload())
{
case 'onload':
$output .= "window.onload={$onload};";
break;
case 'jquery':
$output .= "jQuery(document).ready({$onload});";
break;
case 'mootools':
$output .= "window.addEvent('domready',{$onload});";
break;
}
$output .= '</script>';
return $output;
}
/**
* Method to retrieve the div that the map is loaded into
*
* #return string The body
*
* #since 12.3
*/
public function getBody()
{
$id = $this->getMapId();
$class = $this->getMapClass();
$style = $this->getMapStyle();
$output = "<div id='{$id}'";
if (!empty($class))
{
$output .= " class='{$class}'";
}
if (!empty($style))
{
$output .= " style='{$style}'";
}
$output .= '></div>';
return $output;
}
/**
* Method to get the location information back from an address
*
* #param string $address The address to geocode
*
* #return array An array containing Google's geocode data
*
* #since 12.3
*/
public function geocodeAddress($address)
{
$uri = JUri::getInstance('https://maps.googleapis.com/maps/api/geocode/json');
$uri->setVar('address', urlencode($address));
if (($key = $this->getKey()))
{
$uri->setVar('key', $key);
}
$response = $this->http->get($uri->toString());
if ($response->code < 200 || $response->code >= 300)
{
throw new RuntimeException('Error code ' . $response->code . ' received geocoding address: ' . $response->body . '.');
}
$data = json_decode($response->body, true);
if (!$data)
{
throw new RuntimeException('Invalid json received geocoding address: ' . $response->body . '.');
}
if ($data['status'] != 'OK')
{
if (!empty($data['error_message']))
{
throw new RuntimeException($data['error_message']);
}
return null;
}
return $data['results'][0];
}
}
See Whats the API Key for in Google Maps API V3?
As of June 22, 2016 Google Maps V3 no longer supports keyless access so you need to get a key for every (referrer-)domain which has never had a Google Map on it before.
Get your key here: https://developers.google.com/maps/documentation/javascript/get-api-key
That's just the Joomla google maps class - by itself, the class doesn't do anything. If you're going to copy and paste code - it should be the code you're having trouble with.
You'll need to start by creating a JRegistry options variable, and populate it with stuff like your api key.
Then you'll have to use the class you pasted to create a new map object
$map = new JGoogleEmbedMaps($options)...

SQL "VIEW" in codeigniter

I want to create an SQL view within the codeigniter model. What is the best way of doing this?
I use mutliple models depending on wich table i need to work
application/core/MY_model.php
<?php
/**
* CRUD Model
* A base model providing CRUD, pagination and validation.
*/
class MY_Model extends CI_Model
{
public $table;
public $primary_key;
public $default_limit = 15;
public $page_links;
public $query;
public $form_values = array();
protected $default_validation_rules = 'validation_rules';
protected $validation_rules;
public $validation_errors;
public $total_rows;
public $date_created_field;
public $date_modified_field;
public $native_methods = array(
'select', 'select_max', 'select_min', 'select_avg', 'select_sum', 'join',
'where', 'or_where', 'where_in', 'or_where_in', 'where_not_in', 'or_where_not_in',
'like', 'or_like', 'not_like', 'or_not_like', 'group_by', 'distinct', 'having',
'or_having', 'order_by', 'limit'
);
function __construct()
{
parent::__construct();
}
public function __call($name, $arguments)
{
call_user_func_array(array($this->db, $name), $arguments);
return $this;
}
/**
* Sets CI query object and automatically creates active record query
* based on methods in child model.
* $this->model_name->get()
*/
public function get($with = array(), $include_defaults = true)
{
if ($include_defaults) {
$this->set_defaults();
}
foreach ($with as $method) {
$this->$method();
}
$this->query = $this->db->get($this->table);
return $this;
}
/**
* Query builder which listens to methods in child model.
* #param type $exclude
*/
private function set_defaults($exclude = array())
{
$native_methods = $this->native_methods;
foreach ($exclude as $unset_method) {
unset($native_methods[array_search($unset_method, $native_methods)]);
}
foreach ($native_methods as $native_method) {
$native_method = 'default_' . $native_method;
if (method_exists($this, $native_method)) {
$this->$native_method();
}
}
}
/**
* Call when paginating results.
* $this->model_name->paginate()
*/
public function paginate($with = array())
{
$uri_segment = '';
$offset = 0;
$per_page = $this->default_limit;
$this->load->helper('url');
$this->load->library('pagination');
$this->set_defaults();
foreach ($with as $method) {
$this->$method();
}
$this->total_rows = $this->db->count_all_results($this->table);
$uri_segments = $this->uri->segment_array();
foreach ($uri_segments as $key => $segment) {
if ($segment == 'page') {
$uri_segment = $key + 1;
if (isset($uri_segments[$uri_segment])) {
$offset = $uri_segments[$uri_segment];
}
unset($uri_segments[$key], $uri_segments[$key + 1]);
$base_url = site_url(implode('/', $uri_segments) . '/page/');
}
}
if (!$uri_segment) {
$base_url = site_url($this->uri->uri_string() . '/page/');
}
$config = array(
'base_url' => $base_url,
'uri_segment' => $uri_segment,
'total_rows' => $this->total_rows,
'per_page' => $per_page
);
if ($this->config->item('pagination_style')) {
$config = array_merge($config, $this->config->item('pagination_style'));
}
$this->pagination->initialize($config);
$this->page_links = $this->pagination->create_links();
/**
* Done with pagination, now on to the paged results
*/
$this->set_defaults();
foreach ($with as $method) {
$this->$method();
}
$this->db->limit($per_page, $offset);
$this->query = $this->db->get($this->table);
return $this;
}
function paginate_api($limit, $offset)
{
$this->set_defaults();
if (empty($limit)) {
$limit = $this->default_limit;
}
if (empty($offset)) {
$offset = 0;
}
$this->db->limit($limit, $offset);
return $this->db->get($this->table)->result();
}
/**
* Retrieves a single record based on primary key value.
*/
public function get_by_id($id, $with = array())
{
foreach ($with as $method) {
$this->$method();
}
return $this->where($this->primary_key, $id)->get()->row();
}
public function save($id = NULL, $db_array = NULL)
{
if (!$db_array) {
$db_array = $this->db_array();
}
if (!$id) {
if ($this->date_created_field) {
$db_array[$this->date_created_field] = time();
}
$this->db->insert($this->table, $db_array);
// $this->session->set_flashdata('alert_success', 'Record successfully created.');
return $this->db->insert_id();
} else {
if ($this->date_modified_field) {
$db_array[$this->date_modified_field] = time();
}
$this->db->where($this->primary_key, $id);
$this->db->update($this->table, $db_array);
// $this->session->set_flashdata('alert_success', 'Record successfully updated.');
return $id;
}
}
/**
* Returns an array based on $_POST input matching the ruleset used to
* validate the form submission.
*/
public function db_array()
{
$db_array = array();
$validation_rules = $this->{$this->validation_rules}();
foreach ($this->input->post() as $key => $value) {
if (array_key_exists($key, $validation_rules)) {
$db_array[$key] = $value;
}
}
return $db_array;
}
/**
* Deletes a record based on primary key value.
* $this->model_name->delete(5);
*/
public function delete($id, $others = array())
{
if (!empty($others)) {
foreach ($others as $k => $v) {
$this->db->where($k, $v);
}
} else {
$this->db->where($this->primary_key, $id);
}
return $this->db->delete($this->table);
// $this->session->set_flashdata('alert_success', 'Record successfully deleted.');
}
/**
* Returns the CI query result object.
* $this->model_name->get()->result();
*/
public function result()
{
return $this->query->result();
}
/**
* Returns the CI query row object.
* $this->model_name->get()->row();
*/
public function row()
{
return $this->query->row();
}
/**
* Returns CI query result array.
* $this->model_name->get()->result_array();
*/
public function result_array()
{
return $this->query->result_array();
}
/**
* Returns CI query row array.
* $this->model_name->get()->row_array();
*/
public function row_array()
{
return $this->query->row_array();
}
/**
* Returns CI query num_rows().
* $this->model_name->get()->num_rows();
*/
public function num_rows()
{
return $this->query->num_rows();
}
/**
* Used to retrieve record by ID and populate $this->form_values.
* #param int $id
*/
public function prep_form($id = NULL)
{
if (!$_POST and ($id)) {
$this->db->where($this->primary_key, $id);
$row = $this->db->get($this->table)->row();
foreach ($row as $key => $value) {
$this->form_values[$key] = $value;
}
}
}
/**
* Performs validation on submitted form. By default, looks for method in
* child model called validation_rules, but can be forced to run validation
* on any method in child model which returns array of validation rules.
* #param string $validation_rules
* #return boolean
*/
public function run_validation($validation_rules = NULL)
{
if (!$validation_rules) {
$validation_rules = $this->default_validation_rules;
}
foreach (array_keys($_POST) as $key) {
$this->form_values[$key] = $this->input->post($key);
}
if (method_exists($this, $validation_rules)) {
$this->validation_rules = $validation_rules;
$this->load->library('form_validation');
$this->form_validation->set_rules($this->$validation_rules());
$run = $this->form_validation->run();
$this->validation_errors = validation_errors();
return $run;
}
}
/**
* Returns the assigned form value to a form input element.
* #param type $key
* #return type
*/
public function form_value($key)
{
return (isset($this->form_values[$key])) ? $this->form_values[$key] : '';
}
}
then when i need a model for a specific database i use class inside models
models/content.php
class content_types extends MY_Model
{
function __construct()
{
parent::__construct();
$this->curentuserdata = $this->session->userdata('lg_result');
$this->userprofile = $this->session->userdata('user_profile');
}
public $table = 'content_types';
public $primary_key = 'id';
public $default_limit = 50;
public function default_order_by()
{
$this->db->order_by('id asc');
}
}
then where i need to call the model
$this->modelname->save($id,array());
$this->modelname->where()->get()->row();
so create one for the 'view table' and the others for insert tables