im creating a new module for prestashop 1.5.6 and im having some problems with it.
The module has to send sms to the costumers and it has to be an option of the back-Office menu.
I have created the module with the install and uninstall functions and added the tabs to the back-office menu, but im a newbie in prestashop so i don´t know how to make the AdminMyModuleController.php and when i try to click the tab of the module it says "INVALID SECURITY TOKEN", i don´t know how resolve this issue because i don´t know much of security.
If someone can add me on facebook or whatever to help me would be amazing.
Here is the code of the mymodule.php:
private function _createTab()
{
// Tab Raiz
$data = array(
'id_tab' => '',
'id_parent' => 0,
'class_name' => 'Empty',
'module' => 'mymodule',
'position' => 14, 'active' => 1
);
/* Insert the data to the tab table*/
$res = Db::getInstance()->insert('tab', $data);
//Get last insert id from db which will be the new tab id
$id_tabP = Db::getInstance()->Insert_ID();
//Define tab multi language data
$data_lang = array(
'id_tab' => $id_tabP,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'SMS a clientes'
);
// Now insert the tab lang data
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
// Tab Configuracion
$data = array(
'id_tab' => '',
'id_parent' => $id_tabP,
'class_name' => 'AdminMymodule',
'module' => 'mymodule',
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'Configuracion'
);
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
// Tab Enviar Sms
$data = array(
'id_tab' => '',
'id_parent' => $id_tabP,
'class_name' => 'AdminEnviar',
'module' => 'mymodule',
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'Enviar SMS'
);
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
return true;
}
Thanks
As Lliw said, you must use InstallModuleTab function.
private function installModuleTab($tabClass, $tabName, $idTabParent)
{
$pass = true;
$tab = new Tab();
$tab->name = $tabName;
$tab->class_name = $tabClass;
$tab->module = $this->name; // defined in __construct() function
$tab->id_parent = $idTabParent;
$pass = $tab->save();
return($pass);
}
You can put all in your Install function. For example for your first tab:
public function install()
{
if(!parent::install()
|| !$this->installModuleTab('Empty', array(1 => 'SMS a clientes'), $idTabParent = 0))
return false;
return true;
}
You can set languages with the following array:
array(1 => 'SMS a clientes', 2 => 'Language 2', 3 => 'Language 3')
Then you must create the AdminMyModuleController.php file
It's the wrong way to create a module tab. You should use this function in your install() :
$this->installModuleTab('AdminMyModule', array(1 => 'Attribute description'), $idTabParent = 9);
Then create an AdminMyModuleController.php in your module folder/controllers/admin/AdminMyModuleController.php
But you will need to set some function to see something displayed, i'll make a tutorial for that but until i do it, you can look in another admincontroller from the prestashop core and do the same.
Related
I've created a custom module in Drupal 8 that grab some data from an API, and puts them in the Drupal DB creating a new table.
I want to add this data as the contents of a specific content type.
How can I do that?
here is my code :
<?php
/**
* Implements hook_cron().
*/
function ods_cron() {
$message = 'Cron run: ' . date('Y-m-d H:i:s');
$ods = \Drupal::service('ods.ods');
$conf = \Drupal::service('ods.ods_configuration_request');
if ($conf->isDevelopment()) {
// Development
$response_bond = beforeSendRequest($conf->devUrlExternalBond(), 'GET');
$response_mf = beforeSendRequest($conf->devUrlExternalMutualFund(), 'GET');
} else {
// Production
$parameters_bond = [
'headers' => $conf->headers(),
'authorization' => $conf->basicAuthorization(),
'data_post' => $conf->bodyBond(),
];
$parameters_mf = [
'headers' => $conf->headers(),
'authorization' => $conf->basicAuthorization(),
'data_post' => $conf->bodyMutualFund(),
];
$response_bond = beforeSendRequest($conf->urlExternalBond(), 'POST', $parameters_bond);
$response_mf = beforeSendRequest($conf->urlExternalMutualFund(), 'POST', $parameters_mf);
}
$raw_result_bond = json_decode($response_bond);
$raw_result_mf = json_decode($response_mf);
// Development
if ($conf->isDevelopment()) {
$raw_result_bond = json_decode($raw_result_bond[0]->field_bonds);
$raw_result_mf = json_decode($raw_result_mf[0]->field_api);
}
$BondsProductList = $raw_result_bond->BondsProductInqRs->BondsProductList;
$MFProductInqList = $raw_result_mf->MFProductInqRs->MFProductInqList;
// Bond data store to internal
if ($BondsProductList !== null) {
$bond_datas = [];
foreach ($BondsProductList as $row => $content) {
$bond_datas[] = [
'AskPrice' => number_format($content->AskPrice, 1, '.', ','),
'BidPrice' => number_format($content->BidPrice, 1, '.', ','),
'BuySettle' => number_format($content->BuySettle, 1, '.', ','),
'CouponFreqCode' => $content->CouponFreqCode,
'CouponFreqID' => number_format($content->CouponFreqID),
'CouponRate' => number_format($content->CouponRate, 2, '.', ','),
'IDCurrency' => $content->IDCurrency,
'LastCoupon' => $content->LastCoupon,
'MaturityDate' => $content->MaturityDate,
'MinimumBuyUnit' => number_format($content->MinimumBuyUnit),
'MultipleOfUnit' => number_format($content->MultipleOfUnit),
'NextCoupon' => $content->NextCoupon,
'Penerbit' => $content->Penerbit,
'ProductCode' => $content->ProductCode,
'ProductName' => $content->ProductName,
'ProductAlias' => $content->ProductAlias,
'RiskProfile' => $content->RiskProfile,
'SellSettle' => $content->SellSettle
];
}
$insert_data = $ods->setData(
'bond',
[
'AskPrice', 'BidPrice', 'BuySettle', 'CouponFreqCode', 'CouponFreqID', 'CouponRate', 'IDCurrency',
'LastCoupon', 'MaturityDate', 'MinimumBuyUnit', 'MultipleOfUnit', 'NextCoupon', 'Penerbit',
'ProductCode', 'ProductName', 'ProductAlias', 'RiskProfile', 'SellSettle'
],
$bond_datas
);
if ($insert_data) {
// make response as JSON File and store the file
$ods->makeJsonFile($bond_datas, 'feeds/bonds', 'bond.json');
}
}
// Mutual Fund data store to internal
if ($MFProductInqList !== null) {
$mf_datas = [];
foreach ($MFProductInqList as $row => $content) {
$mf_datas[] = [
'ProductCode' => $content->ProductCode,
'ProductName' => $content->ProductName,
'ProductCategory' => $content->ProductCategory,
'ProductType' => $content->ProductType,
'Currency' => $content->Currency,
'Performance1' => $content->field_1_tahun_mf,
'Performance2' => $content->Performance2,
'Performance3' => $content->Performance3,
'Performance4' => $content->Performance4,
'Performance5' => $content->Performance5,
'UrlProspektus' => $content->UrlProspektus,
'UrlFactSheet' => $content->UrlFactSheet,
'UrlProductFeatureDocument' => $content->UrlProductFeatureDocument,
'RiskProfile' => $content->RiskProfile,
'FundHouseName' => $content->FundHouseName,
'NAVDate' => $content->NAVDate,
'NAVValue' => $content->NAVValue
];
}
$insert_data_mf = $ods->setData(
'mutual_fund',
[
'ProductCode', 'ProductName', 'ProductCategory', 'ProductType', 'Currency', 'Performance1', 'Performance2', 'Performance3',
'Performance4', 'Performance5', 'UrlProspektus', 'UrlFactSheet', 'UrlProductFeatureDocument', 'RiskProfile', 'FundHouseName',
'NAVDate', 'NAVValue'
],
$mf_datas
);
if ($insert_data_mf) {
// make response as JSON File and store the file
$ods->makeJsonFile($mf_datas, 'feeds/mf', 'mutual_fund.json');
}
}
// console log
\Drupal::logger('ods')->notice($message);
}
So can I store the data to pristine drupal 8 table?
First, you need to create the content type in the Drupal 8 backend going to Structure > Content type.
Second you can add a node programmatically like this
use Drupal\node\Entity\Node;
$node = Node::create(array(
'type' => 'your_content_type',
'title' => 'your title',
'langcode' => 'en',
'uid' => '1',
'status' => 1,
'body'=> 'your body',
));
$node->save();
I am working on a plugin for Elgg that keeps track of device ids that are sent to the application when logging in from your mobile phone. For this, I would like to store these device ids in the database and would like to use ElggObjects for this.
This is what I do now:
function initialize() {
$androidTokens = elgg_get_entities(array(
'type' => 'object',
'subtype' => 'androidTokens',
'limit' => 0
));
$iosTokens = elgg_get_entities(array(
'type' => 'object',
'subtype' => 'iosTokens',
'limit' => 0
));
if ($androidTokens == 0) {
$tokenObject = new ElggObject();
$tokenObject->subtype = 'androidTokens';
$tokenObject->tags = array();
$tokenObject->save();
}
if ($iosTokens == 0) {
$tokenObject = new ElggObject();
$tokenObject->subtype = 'iosTokens';
$tokenObject->tags = array();
$tokenObject->save();
}
}
So this generates two ElggObjects that hold ids for android and for ios devices, stored in the metadata field tags. This array of tags can however not be retrieved anymore. When I do:
$tokenObject = elgg_get_entities(array(
'type' => 'object',
'subtype' => $os.'Tokens',
'limit' => 0
));
$tokens = $tokenObject->tags
tokens remains empty. Does someone know what I am doing wrong? Am I using the Elgg objects wrong?
I think the reason you're running into issues there is that elgg_get_entities returns an array of entities.
Am I correct in assuming that you'll only ever have one of each token object subtype? (One for iOS and one for Android?)
If so, I would modify your code as follows:
function initialize() {
$androidTokens = elgg_get_entities(array(
'type' => 'object',
'subtype' => 'androidTokens',
'limit' => 1 // only expecting one entity
));
$iosTokens = elgg_get_entities(array(
'type' => 'object',
'subtype' => 'iosTokens',
'limit' => 1 // only expecting one entity
));
if (count($androidTokens) == 0) {
$tokenObject = new ElggObject();
$tokenObject->subtype = 'androidTokens';
$tokenObject->tags = array();
$tokenObject->save();
}
if (count($iosTokens) == 0) {
$tokenObject = new ElggObject();
$tokenObject->subtype = 'iosTokens';
$tokenObject->tags = array();
$tokenObject->save();
}
}
Later, when grabbing the entity:
$tokenObject = elgg_get_entities(array(
'type' => 'object',
'subtype' => $os.'Tokens',
'limit' => 1 // only grab one
));
$tokens = $tokenObject[0]->tags; // get tag data for first (and only) entity
I have created a class using migrate module but I am unable to migrate entities. my class codes are below please check it and tell me whats the problem with it??
<?php
class ItemOrderXMLMigration extends XMLMigration {
public function __construct() {
parent::__construct(MigrateGroup::getInstance('OrderFeed'));
$this->description = t('Migrate entity from XML file');
//$this->softDependencies = array('WineFileCopy');
$fields = array(
'Number' => t('Number'),
'Date' => t('Date'),
'SubTotal' => t('Sub Total'),
'Discount' => t('Discount'),
'ShippingCharges' => t('Shipping Charges'),
'ShippingChargesDiscount' => t('Shipping Charges Discount'),
'NumItems' => t('NumItems'),
'VATPercentage' => t('VAT Percentage'),
'CurrencyCode' => t('Currency Code'),
'PaymentTypeDesc' => t('Payment Type Desc'),
'OrderState' => t('Order State'),
);
$this->map = new MigrateSQLMap($this->machineName,
array(
'Number' => array(
'type' => 'varchar',
'length' => 225,
'not null' => TRUE,
)
),
MigrateDestinationEntityAPI::getKeySchema('entity_example_basic','first_example_bundle')
);
$xml_folder = DRUPAL_ROOT . '/' . drupal_get_path('module', 'products_import') . '/xml/';
$items_url = $xml_folder . 'OrderFeed.xml';
$item_xpath = '/Orders/Item'; // relative to document
$item_ID_xpath = 'Number'; // relative to item_xpath and gets assembled
// into full path /producers/producer/sourceid
$items_class = new MigrateItemsXML($items_url, $item_xpath, $item_ID_xpath);
$this->source = new MigrateSourceMultiItems($items_class, $fields);
$this->destination = new MigrateDestinationEntityAPI('entity_example_basic','first_example_bundle');
$this->addFieldMapping('field_number', 'Number')
->xpath('Number');
$this->addFieldMapping('field_subtotal', 'SubTotal')
->xpath('SubTotal');
$this->addFieldMapping('field_discount', 'Discount')
->xpath('Discount');
//$this->addUnmigratedDestinations(array('weight'));
}
}
?>
When I import it I got the save error message for all entities: Creating default object from empty value File /var/www/mig/migration/sites/all/modules/migrate_extras/entity_api.inc, line 227
Try the latest or updated migrate module https://www.drupal.org/project/migrate. I think you were using old one which were having some issues to migrate entities.
Why don't you try with a feed importer (Feeds module) using XPath parser module?. It's really easy, and you can use both an uploaded file or a source URL.
Is it possible to create or delete a User programmatically (without SQL) in a typo3 extension?
To CRUD frontend users (fe_users) there already is a Repository and a Model available which you might use in your own Extbase extension. Below...
typo3/sysext/extbase/Classes/Domain
you can find the Model and Repository classes.
some code examples:
function createUser() {
// TypoScript Template mit userid anlegen
// Neue Seite anlegen
$tmpId = 'NEWuser478d8d';
$data['be_users'][$tmpId] = array(
'username' => $this->email,
'password' => $this->password,
'admin' => 0,
'pid' => 0,
'usergroup' => $this->usergroup,
'lang' => 'de',
'email' => $this->email,
'db_mountpoints' => '',
'realName' => $this->realName,
'file_mountpoints' => '',
'fileoper_perms' => (int)$this->conf['fileoper_perms'],
'options' => '2', // mount from group: filemount, aber nicht dbmount
'db_mountpoints' => $this->dbMountPage,
'file_mountpoints' => $this->conf['file_mountpoints'],
'workspace_perms' => 0,
'workspace_id' => 0,
'workspace_preview' => 0
);
$this->debug($data, 'beuser');
$this->tce->start($data,array());
$this->tce->process_datamap();
$this->userid = $this->tce->substNEWwithIDs[$tmpId];
// t3lib_div::debug('Neue Userid:'.$this->userid);
return true;
}
afair you need an be-user which is active, so create one:
/**
* Creates a Be-User
*
* #return void
*/
function setBeUser() {
global $BE_USER;
unset($BE_USER);
$BE_USER = t3lib_div::makeInstance('t3lib_beUserAuth');
$BE_USER->OS = TYPO3_OS;
$BE_USER->setBeUserByUid($this->conf['setBeUserByUid']);
$BE_USER->fetchGroupData();
$BE_USER->backendSetUC();
$GLOBALS['BE_USER'] = $BE_USER;
$GLOBALS['LANG'] = t3lib_div::makeInstance('language');
$GLOBALS['LANG']->init($BE_USER->uc['lang']);
return $BE_USER;
}
init tce:
$this->tce = t3lib_div::makeInstance('t3lib_TCEmain');
$this->tce->BE_USER = $this->setBeUser();
$this->tce->stripslashes_values = 0;
$this->createUser();
I'm trying to migrate my current html site into drupal. I have over 80,000 pages I have to migrate so I thought instead of sitting infront of a computer for 50 years I would create a module. I was able to create a script that extracts the html from each directory and now I got to a road block where I need to create a node. I'm trying to create a new node using node_save(), but when node_save is executed, I get a PDOException error with everything I try. I'm passing in $node, which is an array which is then casted into an object.
PDOException: in field_sql_storage_field_storage_write() (line 424 of /srv/www/htdocs/modules/field/modules/field_sql_storage/field_sql_storage.module).
This is how we are currently creating the node, but it produces an error:
$node= array(
'uid' => $user->uid,
'name' => $user->name,
'type' => 'page',
'language' => LANGUAGE_NONE,
'title' => $html['title'],
'status' => 1,
'promote' => 0,
'sticky' => 0,
'created' => (int)REQUEST_TIME,
'revision' => 0,
'comment' => '1',
'menu' => array(
'enabled' => 0,
'mlid' => 0,
'module' => 'menu',
'hidden' => 0,
'has_children' => 0,
'customized' => 0,
'options' => array(),
'expanded' => 0,
'parent_depth_limit' => 8,
'link_title' => '',
'description' => '',
'parent' => 'main-menu:0',
'weight' => '0',
'plid' => '0',
'menu_name' => 'main-menu',
),
'path' => array(
'alias' => '',
'pid' => null,
'source' => null,
'language' => LANGUAGE_NONE,
'pathauto' => 1,
),
'nid' => null,
'vid' => null,
'changed' => '',
'additional_settings__active_tab' => 'edit-menu',
'log' => '',
'date' => '',
'submit' => 'Save',
'preview' => 'Preview',
'private' => 0,
'op' => 'Save',
'body' => array(LANGUAGE_NONE => array(
array(
'value' => $html['html'],
'summary' => $link,
'format' => 'full_html',
),
)),
'validated' => true,
);
node_save((object)$node);
// Small hack to link revisions to our test user.
db_update('node_revision')
->fields(array('uid' => $node->uid))
->condition('vid', $node->vid)
->execute();
Usually I create a bulkimport.php script in the document root to do this kind of thing.
Here is the code I use for Drupal 7:
<?php
define('DRUPAL_ROOT', getcwd());
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
function _create_node($title="", $body="", $language="und") {
$node = (object)array();
$node->uid = '1';
$node->name = 'admin';
$node->type = 'page';
$node->status = 1;
$node->promote = 0;
$node->sticky = 0;
$node->revision = 1;
$node->language = $language;
$node->title = $title;
$node->body[$language][0] = array(
'value' => $body,
'format' => 'full_html',
);
$node->teaser = '';
$node->log = 'Auto Imported Node';
node_submit($node);
node_save($node);
return $node;
} ### function _create_node
$sith = array(
'Darth Vader' => 'Master: Darth Sidious',
'Darth Sidious' => 'Master: Darth Plagous',
'Darth Maul' => 'Master: Darth Sidious',
'Darth Tyranous' => 'Master: Darth Sidious',
);
foreach($sith as $title=>$body) {
print "Creating Node. Title:[".$title."] \tBody:[".$body."] ";
$node = _create_node($title, $body);
print "\t... Created Node ID: [".$node->nid."]\n";
#print_r($node);
} ### foreach
I was getting exactly the same error as in your original post -
PDOException: in field_sql_storage_field_storage_write()
- etc.
I was already using the stdClass code style shown in the comments above.
The problem turned out to be the pound signs and accented chars in the string I was assigning to the Body field; the strings were coming from a Windows text file.
Converting the string to the Drupal target encoding (UTF-8) worked for me:
$cleaned_string = mb_convert_encoding($html['html'], "UTF-8", "Windows-1252");
$node->body[LANGUAGE_NONE][0]['value'] = $cleaned_string;
$node->body[LANGUAGE_NONE][0]['format'] = 'plain_text';
node_save($node);
Hope this helps someone.
are you using some CMS engine, or it is custom-written website?
in first case, look here http://drupal.org/documentation/migrate
I strongly recommend you to look at the given modules, they should help. Also, as an option, to migrate DB.
You don't need a lot of those blank fields. Also, you can cast the node as an object rather than an array converted to an object.
Your code should be able to be accomplished with this much shorter snippet:
$node = new stdClass();
$node->title = $html['title'];
$node->type = 'page';
$node->body['und'][0]['value'] = $html['html'];
node_save($node);
Also, there's a number of methods that have been developed to mass-import nodes into Drupal - I am a fan of the Feeds module (http://drupal.org/project/feeds). This may require writing a method of exporting your existing content to an intermediary format (CSV or XML), but it works reliably and you can re-import nodes to update content when required.