Is it possible to define some sort of capitalize() or toLowerCase() function when creating Sublime Text 2 Snippets?
For example:
<snippet>
<content><![CDATA[
<?php
class ${1} extends Datamapper
{
var \$has_one = array();
var \$has_many = array();
var \$table = '${1}s';
//constructor and other stuff next...
}
?>
]]></content>
<tabTrigger>dmm</tabTrigger>
</snippet>
This particular snippet helps me create Datamapper ORM models on the fly. When I type dmm the Snippet is fired and my cursor is placed in two areas at the same time; the class's name & the assignment to $table. The first cursor requires capitalization whereas the second cursor should not. Can I force the Snippet's case? Something like {1.toLowerCase}
Simple example, but I can think of other times when I could use this.
You can use substitution and the Perl format string syntax
I have tested this code:
<snippet>
<content><![CDATA[
<?php
class ${1} extends Datamapper
{
var \$has_one = array();
var \$has_many = array();
var \$table = '${1/(.+)/\L\1/g}s';
//constructor and other stuff next...
}
?>
]]></content>
<tabTrigger>dmm</tabTrigger>
</snippet>
Regards,
Armando
Related
I'm trying to create my first component in Joomla but I can't understand how it works really :D
I create a basic component with "Component Creator". (I saved a lot of time...).
Now, I have a table in my DB where I've put my data:
id = 1
name = Andrea
note = Ciao
Now, I want to call it from the page using Joomla Language.
On my models/component.php i wrote:
class Variabili extends JModelLegacy
{
function estraivariabili()
{
$db =& JFactory::getDBO();
$db->setQuery("SELECT * FROM #__table")->loadObjectList();
return $value;
}
}
and on my default.php I wrote
$model=$this->Variabili();
//call the method
$items=$model->estraivariabili();
//print
print_r($items);
But on the page I have this error:
0 Call to undefined method Calcolo_imposteViewCalcoloonline::Variabili()
Where is a mistake?
Please be gentle with me because I'm a beginner: D
Thanks in advance
Andrea
You have committed a few wrongs. I've rewritten your functions so that you can get it. Let's have a look-
The model, it looks almost okay. Just change it like-
class Variabili extends JModelLegacy
{
// Make the function public
public function estraivariabili()
{
$db = &JFactory::getDBO();
// Put the result into a variable first, then return it.
$value = $db->setQuery("SELECT * FROM #__table")->loadObjectList();
return $value;
}
}
And now call the model functions not from default.php, rather than write your code inside view.html.php file.
Inside the display function of view.html.php file first, get the model instance by using getModel() function.
$model = $this->getModel();
Now you can get the items by using this $model class instance.
$this->items = $model->estraivariabili();
This will bring you the data from the database table. And you can use the data at default.php file.
Just try at default.php file-
print_r($this->items);
I am using PrestaShop 1.6.1.0
I have a field in my module supporting different languages, the postProcess() looks like this:
protected function postProcess()
{
$languages = Language::getLanguages(false);
$values = array();
foreach ($languages as $lang)
{
$values['CUSTOMPAGECONFIGURATION_HEADING_TEXT'][$lang['id_lang']] = Tools::getValue('CUSTOMPAGECONFIGURATION_HEADING_TEXT_'.$lang['id_lang']);
}
Configuration::updateValue('CUSTOMPAGECONFIGURATION_HEADING_TEXT', $values['CUSTOMPAGECONFIGURATION_HEADING_TEXT'], true);
return $this->displayConfirmation($this->l('The settings have been updated.'));
}
Problem:
When I try to get this configuration variable value in a custom controller (path: /controllers/front/CustomPageController.php) like shown below, it is not fetching any results:
$headtxt = Configuration::get('CUSTOMPAGECONFIGURATION_HEADING_TEXT');
print_r($headtxt);
exit;
It is not printing anything. I want to fetch this value in a controller, but it does not work and returns an empty string.
Site is using PrestaShop 1.6.1.0 and I tried many codes available. Am I missing something?
I am using this code in new controller created by me for custom page:
$headtxt = Configuration::get('CUSTOMPAGECONFIGURATION_HEADING_TEXT');
print_r($headtxt);
exit;
I expect to output results of configuration variable which saved by the postProcess() method.
Hi #Ankur and Welcome to SO!
In your postProcess() method, you are saving this Configuration value as a multilingual value.
However, while calling the Configuration::get() static method, it seems to me you forgot to mention the language ID, here's the function prototype:
public static function get($key, $idLang = null, $idShopGroup = null, $idShop = null, $default = false)
This should work:
$id_lang = (int)$this->context->cookie->id_lang
$headtxt = Configuration::get('CUSTOMPAGECONFIGURATION_HEADING_TEXT', $id_lang);
print_r($headtxt);
exit;
I have recently started working with Doctrine ORM and I am struggling with the holistic idea of how to get an array of information from a database.
Typically I would do something like this:
$sql = "SELECT * FROM Users";
$userArray = $this->db->fetchAll($sql);
I am able to use setters and getters to update information using my Entity... I have absolutely no clue how to go about using entites to grab information from the DB...
This is what I have:
Controller:
public function usersAction() {
$userFunctions = new UserFunction;
$userArray = $userFunctions->getUsers();
$viewModel = new ViewModel(array('users' => $userArray));
return $viewModel;
UserFunction:
<?php
namespace Administration\Model;
use Doctrine\ORM\EntityManagerInterface;
use Zend\Paginator\Paginator;
use Zend\ServiceManager\ServiceManager;
class UserFunction
{
protected $entityManager;
protected $em;
function __constructor(EntityManagerInterface $entityManager) {
$this->em = $entityManager;
}
public function getUsers()
{
//Do some DB fetching magic and return user list in an array
return array(1,2,3,4,5);
}
}
If you can suggest the HOW to fetch the DATA using ORM Doctrine, that would be much appreciated.
Your data will be returned as an array of entities:
Your "getUsers()" method might look like this:
/**
* Returns an array of User entities.
*/
public function getUsers()
{
return $this->em->getRepository('My\Entity\User')->findAll();
}
The method returns an array of objects (specifically, objects of class \My\Entity\User).
In your view script, you might do something like:
<h1>All Users</h1>
<?php foreach($users as $u): ?>
<?= $u->getUsername(); ?><br/>
<?php endforeach; ?>
So, when you ask about "go about using entites to grab information from the DB...", what you really want to do is "use the EntityManager (and/or EntityRepositories) to grab entities from the DB".
Remember: Entities themselves don't know about persistence (the DB). But the EntityManager and Repositories do.
Finally, based on this question, and another of yours I answered, I suggest you take a look at Repositories in Doctrine. You seem to be reinventing that wheel to some degree.
I have a table which has only two column key-value. I want to create a form which allow user insert 3 pair of key-value settings.
Do I need pass 3 different models to the view? Or is there any possible way to do this?
Check out this link:
http://www.yiiframework.com/doc/guide/1.1/en/form.table
This is considered best form in Yii for updating for creating multiple models.
In essence, for creation you can create a for loop generate as many inputs a you wish to have visible, and in your controller loop over the inputs to create new models.
View File:
for ( $settings as $i=>$setting ) //Settings would be an array of Models (new or otherwise)
{
echo CHtml::activeLabelEx($setting, "[$i]key");
echo CHtml::activeLabelEx($setting, "[$i]key");
echo CHtml::error($setting, "[$i]key");
echo CHtml::activeTextField($setting, "[$i]value");
echo CHtml::activeTextField($setting, "[$i]value");
echo CHtml::error($setting, "[$i]value");
}
Controller actionCreate:
$settings = array(new Setting, new Setting, new Setting);
if ( isset( $_POST['Settings'] ) )
foreach ( $settings as $i=>$setting )
if ( isset( $_POST['Setttings'][$i] ) )
{
$setting->attributes = $_POST['Settings'][$i];
$setting->save();
}
//Render View
To update existing models you can use the same method but instead of creating new models you can load models based on the keys in the $_POST['Settings'] array.
To answer your question about passing 3 models to the view, it can be done without passing them, but to validate data and have the correct error messages sent to the view you should pass the three models placed in the array to the view in the array.
Note: The example above should work as is, but does not provide any verification that the models are valid or that they saved correctly
I'm going to give you a heads up and let you know you could potentially make your life very complicated with this.
I'm currently using an EAV patterned table similar to this key-value and here's a list of things you may find difficult or impossible:
use CDbCriteria mergeWith() to filter related elements on "value"s in the event of a search() (or other)
Filtering CGridView or CListView
If this is just very straight forward key-value with no related entity aspect ( which I'm guessing it is since it looks like settings) then one way of doing it would be:
create a normal "Setting" CActiveRecord for your settings table (you will use this to save entries to your settings table)
create a Form model by extending CFormModel and use this as the $model in your form.
Add a save() method to your Form model that would individually insert key-value pairs using the "Setting" model. Preferably using a transaction incase a key-value pair doesn't pass Settings->validate() (if applicable)
optionally you may want to override the Form model's getAttributes() to return db data in the event of a user wanting to edit an entry.
I hope that was clear enough.
Let me give you some basic code setup. Please note that I have not tested this. It should give you a rough idea though.:
Setting Model:
class Setting extends CActiveRecord
{
public function tableName()
{
return 'settings';
}
}
SettingsForm Model:
class SettingsForm extends CFormModel
{
/**
* Load attributes from DB
*/
public function loadAttributes()
{
$settings = Setting::model()->findAll();
$this->setAttributes(CHtml::listData($settings,'key','value'));
}
/*
* Save to database
*/
public function save()
{
foreach($this->attributes as $key => $value)
{
$setting = Setting::model()->find(array('condition'=>'key = :key',
'params'=>array(':key'=>$key)));
if($setting==null)
{
$setting = new Setting;
$setting->key = $key;
}
$setting->value = $value;
if(!$setting->save(false))
return false;
}
return true;
}
}
Controller:
public function actionSettingsForm()
{
$model = new Setting;
$model->loadAttributes();
if(isset($_POST['SettingsForm']))
{
$model->attributes = $_POST['SettingsForm'];
if($model->validate() && $model->save())
{
//success code here, with redirect etc..
}
}
$this->render('form',array('model'=>$model));
}
form view :
$form=$this->beginWidget('CActiveForm', array(
'id'=>'SettingsForm'));
//all your form element here + submit
//(you could loop on model attributes but lets set it up static for now)
//ex:
echo $form->textField($model,'fieldName'); //fieldName = db key
$this->endWidget($form);
If you want further clarification on a point (code etc.) let me know.
PS: for posterity, if other people are wondering about this and EAV they can check the EAV behavior extention or choose a more appropriate DB system such as MongoDb (there are a few extentions out there) or HyperDex
I am trying to create a method in PHP, that will dynamically bind parameters to a PDO query statement. Unfortunately, in my code below, i can only bind 1 parameter, because adding more parameters will override the previous parameters. Nevertheless, is there a good way to fix this problem?
I hope someone can help. Thanks!
function executeQuery($query, $critArr = null) {
$rows = array();
try {
$stmt=$this->pdo->prepare($query);
if (!empty($critArr)) {
foreach($critArr as $cKey=>$cValue) {
$stmt->bindParam($cKey, $cValue); //!!
}
}
$stmt->execute();
You don't need to do that. The execute method already takes an array of parameters:
function executeQuery($query, $critArr = null) {
$rows = array();
try {
$stmt=$this->pdo->prepare($query);
$stmt->execute($critArr);
// ...
The original problem is that bindParam works by reference, and foreach simply reuses the same variables over and over rather than destroy them at the bottom of the loop and (re)create them at the top. You were effectively re-binding the same variable over and over. (Incidentally, this is the same problem that the mysqli extension has, while it also lacks the convenient already-takes-an-array execute method.)
Your function improved with passing foreach $cValue by reference &$cValue. This should solve your problem.
function executeQuery($query, $critArr = null) {
$rows = array();
try {
$stmt=$this->pdo->prepare($query);
if (!empty($critArr)) {
foreach($critArr as $cKey=>&$cValue) {
$stmt->bindParam($cKey, $cValue); //!!
}
}
$stmt->execute();