Module prestashop - module

I am currently developing a module for prestashop but I can not find information regarding the registration of data in database. Do you have any idea how to do this?
I started by creating my form in my controller like this:
/**
* Assign template vars related to page content
* #see FrontController::initContent()
*/
public function initContent()
{
parent::initContent();
$this->setTemplate('upload.tpl');
}
public function renderForm()
{
$fields_form = array(
'form' => array(
'input' => array(
array(
'type' => 'file',
'label' => $this->l('Insert file here.'),
'name' => 'FILE_NAME',
'required' => true
),
),
'submit' => array(
'title' => $this->l('Save'),
)
),
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = 1;
$helper->fields_value['FILE_NAME'] = "";
$this->fields_form = array();
$helper->submit_action = 'btnSubmit';
return $helper->generateForm(array($fields_form));
}
Thank you

Actually you have to handle response from the form yourself.
Short answer is "do something like this in your module PHP main file" :
protected function postProcess()
{
$errors = array();
if (Tools::isSubmit('submitFormName'))
{
if (!Configuration::updateValue('FORM_INPUT_NAME', Tools::getValue('FORM_INPUT_NAME')))
$errors[] = $this->l('Cannot update settings');
}
}
Configuration::updateValue($key, $value) stores simple strings in DB. You can add some features (see Configuration.php class).
The best way to handle it is to check what they did in modules/mailalerts/mailalerts.php to have a better idea how to do it. It's a good example.

Matt Loye gave you an easy way to save data. But if you want to create your own table you have to do it during the install process. If you want more examples you can explore the modules that are already installed by default.
You might want to tell us the version you are using, because the modules are a little bit different between PS 1.6 and PS 1.7.
The example below is a part of a custom module that I wrote for PS 1.7.
Installation
public function install()
{
if (!parent::install() || !$this->createTables()
) {
return false;
}
return true;
}
protected function createTables()
{
$res = (bool)Db::getInstance()->execute('
CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'my_table` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`column1` varchar(255) NOT NULL,
`column2` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=UTF8;
return $res;
}
Deinstallation
public function uninstall()
{
if (!parent::uninstall() || !$this->deleteTables()){
return false;
}
return true;
}
protected function deleteTables()
{
return Db::getInstance()->execute('
DROP TABLE IF EXISTS `'._DB_PREFIX_.'my_table`;
');
}
Registration of data
protected function postProcess()
{
if (Tools::isSubmit('submitFormName'))
{
//INSERT
Db::getInstance()->execute('
INSERT INTO `'._DB_PREFIX_.'my_table'` (`column1`, `column2`)
VALUES('.$column1.', '.$column2.')'
);
//OR DELETE DATA
Db::getInstance()->execute('
DELETE FROM `'._DB_PREFIX_.'my_table' `
WHERE `id` = '.(int)$id
);
}
}

Related

Override AdminProductsController

I have problem with my custom presta shop module. My module adds new field to product, field name is promotion, is a string. If i add a new product or edit existing i have no problem, i see my new field. But when i have add this field to products list then i don't see this him.
My module:
<?php
if (!defined('_PS_VERSION_'))
exit;
class OverrideTraining extends Module
{
private $_html = '';
public function __construct()
{
$this->name = 'overridetraining';
$this->tab = 'front_office_features';
$this->version = '1.0';
$this->author = 'Pawel Cyrklaf';
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => '1.7.9.9');
$this->need_instance = 0;
$this->bootstrap = true;
$this->displayName = $this->l('Override Training');
$this->description = $this->l('Task to learn override');
parent::__construct();
}
public function install()
{
if (!parent::install() OR
!$this->alterProductTable() OR
!$this->registerHook('displayAdminProductsExtra'))
return false;
return true;
}
public function uninstall()
{
if (!parent::uninstall() OR
!$this->alterProductTable('remove'))
return false;
return true;
}
/**
* #param string $method
* #return bool
*/
public function alterProductTable($method = 'add')
{
if ($method == 'add')
$sql = 'ALTER TABLE ' . _DB_PREFIX_ . 'product ADD `promotion` VARCHAR (255) NOT NULL';
else
$sql = 'ALTER TABLE ' . _DB_PREFIX_ . 'product DROP COLUMN `promotion`';
if (!Db::getInstance()->Execute($sql))
return false;
return true;
}
public function hookDisplayAdminProductsExtra($params)
{
$promotion = Db::getInstance()->getValue('SELECT promotion FROM ' . _DB_PREFIX_ . 'product WHERE id_product = ' . (int)Tools::getValue('id_product'));
$this->context->smarty->assign('promotion', $promotion);
return $this->display(__FILE__, 'adminProductsExtra.tpl');
}
}
and AdminProductsController which i override
<?php
class AdminProductsController extends AdminProductsControllerCore
{
public function __construct()
{
parent::__construct();
$this->fields_list['promotion'] = array(
'title' => $this->l('Promotion'),
'align' => 'text-center',
'class' => 'fixed-width-sm',
'orderby' => false
);
}
}
What i do wrong? I have a nemo's course, on his video all works fine, but at me not working this same code.
I had the same issue on adminOrdersController, an i solved by passing a calback for the value to print try to edit your override by adding 'filter_key' and a 'calback'
public function __construct()
{
parent::__construct();
$this->fields_list['promotion'] = array(
'title' => $this->l('Promotion'),
'align' => 'text-center',
'class' => 'fixed-width-sm',
'filter_key' => 'a!promotion', // syntax: table_alias!field_name
'callback' => 'displayPromotion'
);
}
public function displayPromotion($value) {
return $value ;
}
filter key must be popolated by the alias of the table and with the name of the field that you want to show.
To know what you have to pass as string in filter_key you should check the executed query that show the products in backoffice.
into callback function you can manage or do everything you want with the value before it'll be printed.
To make Prestashop know that there ia a new fields into product table, you have also to override the Product Core class in /classes/product.php
in this file you have to add this public $promotion; just below row 293
then you have to edit the public static $definition = array() of the product table introducing the definition of your new field, so you have to put into definition array this
'promotion' => array(
'type' => self::TYPE_STRING,
'lang' => true, // or false if don't need to translate this field
'validate' => 'isCleanHtml',
'size' => 255
),
now your field should be visible in backoffice product list

Add custom field in Prestashop 1.7.6 category with a module. How to save in database?

I'm creating a module in Prestashop 1.7.6 to add some custom fields in my categories administration page. Here is my code (from this source in French, new Symfony model used) :
modules/categorycustomfields/categorycustomfields.php
class Categorycustomfields extends Module
{
protected $config_form = false;
public function __construct()
{
$this->name = 'categorycustomfields';
$this->tab = 'administration';
$this->version = '1.0.0';
$this->author = 'abc';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Category Custom Fields');
$this->description = $this->l('Add custom fields to category');
$this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
}
public function install()
{
if (!parent::install()
// Install Sql du module
|| !$this->_installSql()
//Installation des hooks
|| !$this->registerHook('actionAdminCategoriesControllerSaveAfter')
|| !$this->registerHook('actionAdminCategoriesFormModifier')
) {
return false;
}
return true;
}
public function hookActionCategoryFormBuilderModifier(array $params)
{
//Récupération du form builder
/** #var \Symfony\Component\Form\FormBuilder $formBuilder */
$formBuilder = $params['form_builder'];
//Ajout de notre champ spécifique
$formBuilder->add('color',
\Symfony\Component\Form\Extension\Core\Type\TextType::class,
[
'label' => $this->l('Color'), //Label du champ
'required' => false, //Requis ou non
'constraints' => [ //Contraintes du champs
new \Symfony\Component\Validator\Constraints\Length([
'max' => 20,
'maxMessage' => $this->l('Max caracters allowed : 20'),
]),
],
'data' => '' //Valeur du champ
]
);
$formBuilder->setData($params['data'], $params);
}
public function hookActionAfterCreateCategoryFormHandler(array $params)
{
$this->updateData($params['form_data'], $params);
}
public function hookActionAfterUpdateCategoryFormHandler(array $params)
{
$this->updateData($params['form_data'], $params);
}
//params not well used but for examples
protected function updateData(array $data, $params)
{
$insertData = array(
'id_category' => (int)$params['id'],
'id_lang' => (int)$this->context->language->id,
'color' => $data['color'],
);
//Update database
Db::getInstance()->insert( "ps_category_lang ", $insertData);
}
}
In method updateData(), I get my custom field with the category ID and lang ID and I use the Db Class method insert() to update my color field in database (the color field is well created).
But when I save or update, I have this error : [PrestaShopDatabaseException code 0].
Maybe the database method is not good? Could somebody tell me how to save this data?
Thanks !
$cat = new Category((int)$params['id']);
$cat->color= $data['color'];
$cat->update();
Try to update like this:
$query = "UPDATE `"._DB_PREFIX_."category_lang` SET color='".$data['color']."' WHERE id_category = '".(int)$params['id']."' ";
Db::getInstance()->Execute($query);
I made this module, so maybe it's useful ps_customercedula

Using Multiple Database Connection Not Working For Extension

I am doing multiple database connection using the tutorial at http://www.yiiframework.com/wiki/544/multiple-database-connection-select-database-based-on-login-user-id-dynamic/ . The code is working fine in the model. But the problem is I am using an extension where I am using db connection using Yii::app()->db; Here I am getting exception Property "CWebApplication.dbadvert" is not defined. The controller of the extension is extended from CExtController. Please help.
In the example you're referring dbadvert is set up for custom active record class RActiveRecord, not for the web application.
If you want to use it like Yii::app()->dbadvert, you would need to set it up in components section of your config.php like this
'dbadvert' => array(
'class' => 'CDbConnection'
*params here*
),
UPD
You can create a wrapper component for CDbConnection, that will change the connection string any way you want and put in as a webapp component.
<?php
class CMultiuserDatabaseConnection extends CApplicationComponent {
public function __call($name, $params) {
$db = $this->db;
return call_user_func_array(($db, $name), $params);
}
public $dbConnectionClass = 'CDbConnection';
public $connections = null;
public $defaultConfiguration = null;
public function getDatabaseConfiguration($user) {
if (!$this->connections) { return array(); }
return array_key_exists($user, $this->connections) ? $this->connections[$user] : $this->defaultConfiguration;
}
public function getDb() {
$user = Yii::app()->user;
if ($user->isGuest) { return false; }
$username = $user->name;
$config = $this->getDatabaseConfiguration($username);
if (!$config) { return false; }
$dsn = array_key_exists('dsn', $config) ? $config['dsn'] : null;
if (!$dsn) { return false; }
$user = array_key_exists('user', $config) ? $config['user'] : null;
$password = array_key_exists('password', $config) ? $config['password'] : null;
$result = new $this->dbConnectionClass($dsn, $user, $password);
return $result;
}
}
That's a crude example of component, which you can set up as your 'db' component and then you'll get 'connections' option for storing the per-user configuration in that way:
'components' => array(
...
'db' => array(
'class' => "CMultiuserDatabaseConnection",
'connections' => array(
"first-user-name" => array(
// just another db configuration here, for user-one
),
"second-user-name" => array(
// just another db configuration herer, for user two
),
...
),
'defaultConfiguration' => array(
/*
* here goes configuration for all other user, that were not specified
* in connections.
*/
),
),
...
),
I wrote the query for the extension in a model as functions. and in the CExtController created an instance of the model. Then I called those functions and everything is working fine.

call model in zend form using dependencies + zend framework 2

I am trying to fetch my category model in zend form for working out with select element with zend framework 2.
after lot of code searching I found I can either inject or pull dependencies.
Following code I did in my module.php
I want categoryTable.php(model) file in my CategoryForm.php
public function getServiceConfig()
{
return array(
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
'Category\Form\CategoryForm' => function ($sm) {
$service = $sm->get('Category\Model\CategoryTable');
$form = new Form;
$form->setService($service);
return $form;
}
),
);
}
then I put following code in my controller.
$form = $this->getServiceLocator()->get("Category\Form\CategoryForm");
Then I Put following code in my CategoryForm.php
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceLocator();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
And then I call it in same file like this way
public function __construct($name = null)
{
parent::__construct('category');
echo "<pre>";print_r($this->getCategoryTable());die;
.... other code
I found this error
Fatal error: Call to undefined method Category\Form\CategoryForm::getServiceLocator() in D:\wamp\www\zendapp\module\Category\src\Category\Form\CategoryForm.php on line 120
please help. and am I missing something?
I found the solution
Step :1
Here is my module.php code
public function getServiceConfig()
{
return array(
'invokables' => array(
'Category\Form\CategoryForm' => 'Category\Form\CategoryForm',
),
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
Step :2
Then in controller I made this change
// $form = new CategoryForm();
// Service locator now injected
$form = $this->getServiceLocator()->get('Category\Form\CategoryForm');
Step :3
Then In my categoryForm.php I made below changes
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
protected $serviceManager;
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceManager();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
protected function getCatList()
{
$groups = $this->getCategoryTable()->fetchAll();
return $groups;
}
public function getServiceManager()
{
if ( is_null($this->serviceManager) ) {
throw new Exception('The ServiceManager has not been set.');
}
return $this->serviceManager;
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
// Call the init function of the form once the service manager is set
$this->init();
return $this;
}
public function __construct($name = null) // constructor I finished immediately
{
parent::__construct('category');
}
I add INIT() function to fetch servicemanager
public function init()
{
$this->setAttribute('method', 'post');
$options = array();
foreach ($this->getCatList() as $cat) {
$options[$cat->id] = $cat->title;
}
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'parent_id',
'options' => array(
'label' => 'Parent Category',
'empty_option' => 'Please choose Parent Category',
'value_options' => $options,
),
));
}
Hope this will help who are new ZF2.

yii user-management edit field

I have managed to set-up yii-user-management. Thanks to help from here.
However, when I am in profile/fields/admin .
I click on edit field and then change the field from required 'no' to 'yes' in the dropdown, then save, but nothing happens.
I also get :
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 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 '(0) NOT NULL DEFAULT 0' at line 1. The SQL statement executed was: ALTER TABLE profile ADD `` (0) NOT NULL DEFAULT 0
When creating a field.
Let me know if you need some code or files. Any help appreciated.
Here is the profile/models/YumProfileField.php
class YumProfileField extends YumActiveRecord
{
const VISIBLE_HIDDEN=0;
const VISIBLE_ONLY_OWNER=1;
const VISIBLE_REGISTER_USER=2;
const VISIBLE_USER_DECISION=3;
const VISIBLE_PUBLIC=4; // Field is public even if the user decides to hide it
/**
* Returns the static model of the specified AR class.
* #param string $className
* #return YumProfileField
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function isPublic($user = null) {
if($user == null)
$user = Yii::app()->user->id;
if(!$this->visible)
return false;
if($privacy = YumUser::model()->findByPk($user)->privacy) {
if($privacy->public_profile_fields & pow(2, $this->id))
return true;
}
return false;
}
public function tableName()
{
$this->_tableName = Yum::module('profile')->profileFieldTable;
return $this->_tableName;
}
public function scopes()
{
return array(
'forAll'=>array(
'condition'=>'visible='.self::VISIBLE_PUBLIC,
),
'forUser'=>array(
'condition'=>'visible>='.self::VISIBLE_REGISTER_USER,
),
'forOwner'=>array(
'condition'=>'visible>='.self::VISIBLE_ONLY_OWNER,
),
);
}
public static function itemAlias($type,$code=NULL) {
$_items = array(
'field_type' => array(
'INTEGER' => Yum::t('INTEGER'),
'VARCHAR' => Yum::t( 'VARCHAR'),
'TEXT'=> Yum::t( 'TEXT'),
'DATE'=> Yum::t( 'DATE'),
'DROPDOWNLIST' => Yum::t('DROPDOWNLIST'),
'FLOAT'=> Yum::t('FLOAT'),
'BOOL'=> Yum::t('BOOL'),
'BLOB'=> Yum::t('BLOB'),
'BINARY'=> Yum::t('BINARY'),
'FILE'=> 'FILE',
),
'required' => array(
'0' => Yum::t('No'),
'1' => Yum::t('Yes'),
),
'visible' => array(
self::VISIBLE_USER_DECISION => Yum::t('Let the user choose in privacy settings'),
self::VISIBLE_PUBLIC => Yum::t('For all'),
self::VISIBLE_REGISTER_USER => Yum::t('Registered users'),
self::VISIBLE_ONLY_OWNER => Yum::t('Only owner'),
self::VISIBLE_HIDDEN => Yum::t('Hidden'),
),
);
if (isset($code))
return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
else
return isset($_items[$type]) ? $_items[$type] : false;
}
}
The YumFieldsController:
class YumFieldsController extends YumController
{
const PAGE_SIZE=10;
public function accessRules()
{
return array(
array('allow',
'actions'=>array('index', 'create', 'update', 'view', 'admin','delete'),
'users'=>array(Yii::app()->user->name),
'expression' => 'Yii::app()->user->isAdmin()'
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
public function actionView()
{
$this->layout = Yum::module()->adminLayout;
$this->render('view',array(
'model'=>$this->loadModel('YumProfileField'),
));
}
public function actionCreate() {
$this->layout = Yum::module()->adminLayout;
$model = new YumProfileField;
// add to group?
if(isset($_GET['in_group']))
$model->field_group_id=$_GET['in_group'];
if(isset($_POST['YumProfileField'])) {
$model->attributes = $_POST['YumProfileField'];
$field_type = $model->field_type;
if($field_type == 'DROPDOWNLIST')
$field_type = 'INTEGER';
if($model->validate()) {
$sql = 'ALTER TABLE '.YumProfile::model()->tableName().' ADD `'.$model->varname.'` ';
$sql .= $field_type;
if ($field_type!='TEXT' && $field_type!='DATE')
$sql .= '('.$model->field_size.')';
$sql .= ' NOT NULL ';
if ($model->default)
$sql .= " DEFAULT '".$model->default."'";
else
$sql .= (($field_type =='TEXT' || $model->field_type=='VARCHAR')?" DEFAULT ''":" DEFAULT 0");
$model->dbConnection->createCommand($sql)->execute();
$model->save();
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
));
}
public function actionUpdate()
{
$this->layout = Yum::module()->adminLayout;
$model = $this->loadModel('YumProfileField');
if(isset($_POST['YumProfileField']))
{
$model->attributes=$_POST['YumProfileField'];
// ALTER TABLE `test` CHANGE `profiles` `field` INT( 10 ) NOT NULL
// ALTER TABLE `test` CHANGE `profiles` `description` INT( 1 ) NOT NULL DEFAULT '0'
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
public function actionDelete()
{
$this->layout = Yum::module()->adminLayout;
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$model = $this->loadModel('YumProfileField');
$sql = 'ALTER TABLE '.YumProfile::model()->tableName().' DROP `'.$model->varname.'`';
if ($model->dbConnection->createCommand($sql)->execute()) {
$model->delete();
}
if(!isset($_POST['ajax']))
$this->redirect(array('index'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
public function actionIndex()
{
$this->layout = Yum::module()->adminLayout;
$dataProvider=new CActiveDataProvider('YumProfileField', array(
'pagination'=>array(
'pageSize'=>self::PAGE_SIZE,
),
'sort'=>array(
'defaultOrder'=>'position',
),
));
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
public function actionAdmin()
{
$this->layout = Yum::module()->adminLayout;
$dataProvider=new CActiveDataProvider('YumProfileField', array(
'pagination'=>array(
'pageSize'=>self::PAGE_SIZE,
),
'sort'=>array(
'defaultOrder'=>'position',
),
));
$this->render('admin',array(
'dataProvider'=>$dataProvider,
));
}
}
YumProfile.php model
class YumProfile extends YumActiveRecord
{
const PRIVACY_PRIVATE = 'private';
const PRIVACY_PUBLIC = 'public';
/**
* #var array of YumProfileFields
*/
static $fields=null;
public function init()
{
parent::init();
// load profile fields only once
$this->loadProfileFields();
}
public function afterSave() {
if($this->isNewRecord)
Yii::log(Yum::t( 'A profile been created: {profile}', array(
'{profile}' =>json_encode($this->attributes))));
else
Yii::log(Yum::t( 'A profile been update: {profile}', array(
'{profile}' => json_encode($this->attributes))));
return parent::afterSave();
}
public function recentComments($count = 3) {
$criteria = new CDbCriteria;
$criteria->condition = 'id = ' .$this->id;
$criteria->order = 'createtime DESC';
$criteria->limit = $count;
return YumProfileComment::model()->findAll($criteria);
}
public function beforeValidate() {
if($this->isNewRecord)
$this->timestamp = time();
return parent::beforeValidate();
}
/**
* #param string $className
* #return YumProfile
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
// All fields that the user has activated in his privacy settings will
// be obtained and returned for the use in the profile view
public function getPublicFields() {
if(!Yum::module('profile')->enablePrivacySetting)
return false;
$fields = array();
if($privacy = YumUser::model()
->cache(500)
->with('privacy')
->findByPk($this->user_id)
->privacy->public_profile_fields) {
$i = 1;
foreach(YumProfileField::model()->cache(3600)->findAll() as $field) {
if(
(($i & $privacy)
&& $field->visible != YumProfileField::VISIBLE_HIDDEN)
|| $field->visible == YumProfileField::VISIBLE_PUBLIC)
$fields[] = $field;
$i*=2;
}
}
return $fields;
}
/**
* Returns resolved table name
* #return string
*/
public function tableName()
{
$this->_tableName = Yum::module('profile')->profileTable;
return $this->_tableName;
}
public function rules()
{
$required = array();
$numerical = array();
$rules = array();
$safe = array();
foreach (self::$fields as $field) {
$field_rule = array();
if ($field->required == 1)
array_push($required, $field->varname);
if ($field->field_type == 'int'
|| $field->field_type == 'FLOAT'
|| $field->field_type =='INTEGER'
|| $field->field_type =='BOOLEAN')
array_push($numerical, $field->varname);
if ($field->field_type == 'DROPDOWNLIST')
array_push($safe, $field->varname);
if ($field->field_type == 'VARCHAR' || $field->field_type == 'TEXT') {
$field_rule = array($field->varname,
'length',
'max'=>$field->field_size,
'min' => $field->field_size_min);
if ($field->error_message)
$field_rule['message'] = Yum::t($field->error_message);
array_push($rules,$field_rule);
}
if ($field->match) {
$field_rule = array($field->varname,
'match',
'pattern' => $field->match);
if ($field->error_message)
$field_rule['message'] = Yum::t( $field->error_message);
array_push($rules,$field_rule);
}
if ($field->range) {
// allow using commas and semicolons
$range=explode(';',$field->range);
if(count($range)===1)
$range=explode(',',$field->range);
$field_rule = array($field->varname,'in','range' => $range);
if ($field->error_message)
$field_rule['message'] = Yum::t( $field->error_message);
array_push($rules,$field_rule);
}
if ($field->other_validator) {
$field_rule = array($field->varname,
$field->other_validator);
if ($field->error_message)
$field_rule['message'] = Yum::t( $field->error_message);
array_push($rules, $field_rule);
}
}
array_push($rules,
array(implode(',',$required), 'required'));
array_push($rules,
array(implode(',',$numerical), 'numerical', 'integerOnly'=>true));
array_push($rules,
array(implode(',',$safe), 'safe'));
$rules[] = array('allow_comments, show_friends', 'numerical');
$rules[] = array('email', 'unique');
$rules[] = array('email', 'CEmailValidator');
$rules[] = array('privacy', 'safe');
return $rules;
}
public function relations()
{
$relations = array(
'user' => array(self::BELONGS_TO, 'YumUser', 'user_id'),
'comments' => array(self::HAS_MANY, 'YumProfileComment', 'profile_id'),
);
$fields = Yii::app()->db->cache(3600)->createCommand(
"select * from ".YumProfileField::model()->tableName()." where field_type = 'DROPDOWNLIST'")->queryAll();
foreach($fields as $field) {
$relations[ucfirst($field['varname'])] = array(
self::BELONGS_TO, ucfirst($field['varname']), $field['varname']);
}
return $relations;
}
// Retrieve a list of all users that have commented my profile
// Do not show my own profile visit
public function getProfileCommentators() {
$commentators = array();
foreach($this->comments as $comment)
if($comment->user_id != Yii::app()->user->id)
$commentators[$comment->user_id] = $comment->user;
return $commentators;
}
public function getProfileFields() {
$fields = array();
if(self::$fields)
foreach(self::$fields as $field) {
$varname = $field->varname;
$fields[$varname] = Yum::t($varname);
}
return $fields;
}
public function name() {
return sprintf('%s %s', $this->firstname, $this->lastname);
}
public function attributeLabels()
{
$labels = array(
'id' => Yum::t('Profile ID'),
'user_id' => Yum::t('User ID'),
'privacy' => Yum::t('Privacy'),
'show_friends' => Yum::t('Show friends'),
'allow_comments' => Yum::t('Allow profile comments'),
);
if(self::$fields)
foreach (self::$fields as $field)
$labels[$field->varname] = Yum::t($field->title);
return $labels;
}
/**
* Load profile fields.
* Overwrite this method to get another set of fields
* Makes use of cache so the amount of sql queries per request is reduced
* #since 0.6
* #return array of YumProfileFields or empty array
*/
public function loadProfileFields()
{
if(self::$fields===null)
{
self::$fields=YumProfileField::model()->cache(3600)->findAll();
if(self::$fields==null)
self::$fields=array();
}
return self::$fields;
}
}
looks like you're trying to add a column with no name or type? MySQL ALTER TABLE examples.
Also, check your db user has permissions to ALTER TABLE.