How To Use External Class In YII2 Step By Step [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
So i have a class i have used couple of times for other non YII projects but now i want to use the same class in a YII2 project. I have done some searches but i kind of got stuck along the way. Below is what i have done so far:
I created a folder called "utility" in the vendor directory, the utility folder contains my class named "AT_Response.class.php". So my question is how do i include or call and use this class in my model or controller.
I have checked some links like :
https://www.yiiframework.com/doc/guide/2.0/en/tutorial-yii-integration
https://forum.yiiframework.com/t/not-understanding-how-to-use-external-php-library/79679
Class Code:
<?php
class AT_Response {
static private $response = array
(
'9999' => array('description' => "Unexpected Response", 'definite' => true, 'status' => "Indeterminate"),
'00' => array('description' => "Success", 'definite' => true, 'status' => "Success"),
'NNC_AUTH_01' => array('description' => /*"Status unknown, please wait for settlement report"*/"System Error", 'definite' => true, 'status' => "Failure"),
'NNC_VTU_01' => array('description' => "Ttimed out", 'definite' => false, 'status' => "Indeterminate"),
'NNC_VTU_02' => array('description' => "Exceeded max number of requests for Phone number per time period", 'definite' => true, 'status' => "Failure"),
'NNC_VTU_03' => array('description' => "Invalid target MSISDN supplied", 'definite' => true, 'status' => "Failure"),
'-1' => array('description' => "Not successful", 'definite' => false, 'status' => "Failure"),
);
static function getResponseByCode($respCode) {
if (isset(self::$response[$respCode]))
return self::$response[$respCode];
//else
return self::$response['9999'];
}
}
Thanks

With a few changes you can use any custom class as a helper component. You need to use namespace and use statement for the existing class you have, see the below
<?php
namespace app\components;
class Response
{
/**
* #var array
*/
private static $response = array
(
'9999' => array('description' => "Unexpected Response", 'definite' => true, 'status' => "Indeterminate"),
'00' => array('description' => "Success", 'definite' => true, 'status' => "Success"),
'NNC_AUTH_01' => array('description' => /*"Status unknown, please wait for settlement report"*/"System Error", 'definite' => true, 'status' => "Failure"),
'NNC_VTU_01' => array('description' => "Ttimed out", 'definite' => false, 'status' => "Indeterminate"),
'NNC_VTU_02' => array('description' => "Exceeded max number of requests for Phone number per time period", 'definite' => true, 'status' => "Failure"),
'NNC_VTU_03' => array('description' => "Invalid target MSISDN supplied", 'definite' => true, 'status' => "Failure"),
'-1' => array('description' => "Not successful", 'definite' => false, 'status' => "Failure")
);
/**
* #param $respCode
*/
public static function getResponseByCode($respCode)
{
if (isset(self::$response[$respCode])) {
return self::$response[$respCode];
}
return self::$response['9999'];
}
}
Save the Above class in a file called Response.php in app\components folder if using basic-app or common\components if you are using advanced-app but dont forget to change the namespace in the code.
You can then call the function getResponseByCode() like app\components\Response::getResponseByCode($responseCode) or common\components\Response::getResponseByCode($responseCode)

Related

How to read function php and create a file xml [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I need to read this function and create an xml with the title, description and etc fields.
then the table.
public function defineCustomTemplate()
{
$this->setNmfile(302444);
$this->setNmoperation("CPTEVALITHAB");
$this->setNmimport(302433);
$customTemplate = array();
$customTemplate[] = array('column' => 'nmfield01', 'term' => 103571, 'dataType' => 2, 'precision' => 50, 'description' => 213795, 'required' => 1);
$customTemplate[] = array('column' => 'nmfield02', 'term' => 102213, 'dataType' => 2, 'precision' => 50, 'description' => 302440, 'required' => 1);
$customTemplate[] = array('column' => 'nmfield03', 'term' => 302442, 'dataType' => 2, 'precision' => 50, 'description' => 302442, 'required' => 1);
$customTemplate[] = array('column' => 'nmfield04', 'term' => 302443, 'dataType' => 2, 'precision' => 50, 'description' => 302443, 'required' => 1);
return $customTemplate;
}
this function appears in several classes of the project and I would like to capture everywhere it is displayed and create the xml.
can someone help me?
You can use the SimpleXMLElement class in PHP to create an XML document with the data from the defineCustomTemplate() function.
approximate solution without fields hardcoding
$sxml = new \SimpleXMLElement(('<?xml version="1.0" encoding="utf-8"?><file></file>'));
$sxml->addAttribute('filename', $Nmfile);
$operation = $sxml->addChild('operations');
$operation->addAttribute('opname', $Nmoperation);
foreach ($customTemplate as $key => $item) {
$serverKeys = array_keys($item);
$import = $operation->addChild('import');
$import->addAttribute('import_id', $Nmimport);
foreach ($serverKeys as $i => $name) {
$ops = $import->addChild($name);
$ops->addAttribute($name,$item[$name]);
}
}
var_dump($sxml->asXML());
output template:
<?xml version="1.0" encoding="utf-8"?>
<file filename="302444">
<operations opname="CPTEVALITHAB">
<import import_id="0">
<column column="nmfield02"/>
...
</import>
</operations>
</file>

Get CHAT_WRITE_FORBIDDEN using MadelineProto with Telegram API

I'm using the MadelineProto project for php to interact with Telegram API.
Maybe this error has nothing to do with MadelineProto... anyway, I successfully created a supergroup but any other method I call after, gives me a CHAT_WRITE_FORBIDDEN error.
Can't find anything in Telegram Documentation about why I'm getting this error and how to solve.
This is my code:
$MadelineProto = new MadelineProtoAPI('session.madeline', $settings);
$MadelineProto->async(false);
$MadelineProto->start();
// successfully create the group
$updates = $MadelineProto->channels->createChannel([
'megagroup' => true,
'title' => 'Test group',
'about' => 'Test group description',
]);
foreach($updates as $update) {
// try to invite other users --> CHAT_WRITE_FORBIDDEN
$updates = $MadelineProto->channels->inviteToChannel([
'channel' => $update,
'users' => ['########']
]);
// try to change admin rights --> CHAT_WRITE_FORBIDDEN
$updates = $MadelineProto->channels->editAdmin([
'channel' => $update,
'user_id' => '########',
'admin_rights' => [
'_' => 'chatAdminRights',
'change_info' => true,
'post_messages' => true,
'edit_messages' => true,
'delete_messages' => true,
'ban_users' => true,
'invite_users' => true,
'pin_messages' => true,
'add_admins' => true,
'anonymous' => true,
],
'rank' => ''
]);
}
What I'm doing wrong?
Thanks
It seems that the problem was due to the value passed to the 'channel' property. Instead of passing the $update variable, I passed directly the channel id in the form "channel#1234567890" and finally got a correct answer from Telegram.

Prestashop 1.6.1.11 If user not logged show (This.)

Currently trying to dig my way around Prestashop, 1.6.1.11. I understand it a little bit but I wouldn't say I'm experienced.
I'm after a way to check if the user is logged in, which I have found examples for this elsewhere using .tpl files. However I need to action a response if the user is not logged in The thread I found is the reverse of which.
e.g. If user is not logged show element.
I found this line {if $logged} ..... {/if} , on the prestashop forums, but the thread is rather old and I'm not sure if this holds up as it dates back to version 1.5. I may be showing my inexperience here, but you don't know until you ask.
As a bit of background as to what it is specifically that I'm trying to achieve is to display a full width / height image with a sign-in element layered over top within the center.
I want to essentially give the user only one element to interact with and use to sign in.
I hope I have explained myself well enough, any help is appreciated. I'll keep looking and if I find anything useful I'll post it here.
Edit
Link to Prestashop thread.
My Own Prestashop question.
So after some digging, I was able to use the following to get the function I desired.
<!-- Check Login -->
<div id="check-log">
{if $is_logged}
<a href=".." id="Logout" />Logout</a>
{else}
<a href=".." id="Login" />Login</a>
{/if}
</div>
This code should be placed within the header.tpl Theme file.
This variable is defined in class /classes/controller/FrontController.php in method init():
$this->context->smarty->assign(array(
// Useful for layout.tpl
'mobile_device' => $this->context->getMobileDevice(),
'link' => $link,
'cart' => $cart,
'currency' => $currency,
'currencyRate' => (float)$currency->getConversationRate(),
'cookie' => $this->context->cookie,
'page_name' => $page_name,
'hide_left_column' => !$this->display_column_left,
'hide_right_column' => !$this->display_column_right,
'base_dir' => _PS_BASE_URL_.__PS_BASE_URI__,
'base_dir_ssl' => $protocol_link.Tools::getShopDomainSsl().__PS_BASE_URI__,
'force_ssl' => Configuration::get('PS_SSL_ENABLED') && Configuration::get('PS_SSL_ENABLED_EVERYWHERE'),
'content_dir' => $protocol_content.Tools::getHttpHost().__PS_BASE_URI__,
'base_uri' => $protocol_content.Tools::getHttpHost().__PS_BASE_URI__.(!Configuration::get('PS_REWRITING_SETTINGS') ? 'index.php' : ''),
'tpl_dir' => _PS_THEME_DIR_,
'tpl_uri' => _THEME_DIR_,
'modules_dir' => _MODULE_DIR_,
'mail_dir' => _MAIL_DIR_,
'lang_iso' => $this->context->language->iso_code,
'lang_id' => (int)$this->context->language->id,
'language_code' => $this->context->language->language_code ? $this->context->language->language_code : $this->context->language->iso_code,
'come_from' => Tools::getHttpHost(true, true).Tools::htmlentitiesUTF8(str_replace(array('\'', '\\'), '', urldecode($_SERVER['REQUEST_URI']))),
'cart_qties' => (int)$cart->nbProducts(),
'currencies' => Currency::getCurrencies(),
'languages' => $languages,
'meta_language' => implode(',', $meta_language),
'priceDisplay' => Product::getTaxCalculationMethod((int)$this->context->cookie->id_customer),
'is_logged' => (bool)$this->context->customer->isLogged(),
'is_guest' => (bool)$this->context->customer->isGuest(),
'add_prod_display' => (int)Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'),
'shop_name' => Configuration::get('PS_SHOP_NAME'),
'roundMode' => (int)Configuration::get('PS_PRICE_ROUND_MODE'),
'use_taxes' => (int)Configuration::get('PS_TAX'),
'show_taxes' => (int)(Configuration::get('PS_TAX_DISPLAY') == 1 && (int)Configuration::get('PS_TAX')),
'display_tax_label' => (bool)$display_tax_label,
'vat_management' => (int)Configuration::get('VATNUMBER_MANAGEMENT'),
'opc' => (bool)Configuration::get('PS_ORDER_PROCESS_TYPE'),
'PS_CATALOG_MODE' => (bool)Configuration::get('PS_CATALOG_MODE') || (Group::isFeatureActive() && !(bool)Group::getCurrent()->show_prices),
'b2b_enable' => (bool)Configuration::get('PS_B2B_ENABLE'),
'request' => $link->getPaginationLink(false, false, false, true),
'PS_STOCK_MANAGEMENT' => Configuration::get('PS_STOCK_MANAGEMENT'),
'quick_view' => (bool)Configuration::get('PS_QUICK_VIEW'),
'shop_phone' => Configuration::get('PS_SHOP_PHONE'),
'compared_products' => is_array($compared_products) ? $compared_products : array(),
'comparator_max_item' => (int)Configuration::get('PS_COMPARATOR_MAX_ITEM'),
'currencySign' => $currency->sign, // backward compat, see global.tpl
'currencyFormat' => $currency->format, // backward compat
'currencyBlank' => $currency->blank, // backward compat
));
// Deprecated
$this->context->smarty->assign(array(
'id_currency_cookie' => (int)$currency->id,
'logged' => $this->context->customer->isLogged(),
'customerName' => ($this->context->customer->logged ? $this->context->cookie->customer_firstname.' '.$this->context->cookie->customer_lastname : false)
));

Troubleshooting dynamic dropdowns in SugarCRM 6.5

I had asked a question here a while back about setting up database populated dropdowns for SugarCRM. I received a really good answer and, after more php studies and a dev instance running, I decided to give it a shot. The instructions I followed can be found here. After I run the repair and rebuild, I would expect to see the custom field in my Fields list under the module in studio, but have not been able to find it. The module is named Makers (a1_makers as a database table). For good orders sake, there were no errors when I repaired/rebuilt after saving the files. Per the instructions, I first created a php file with a custom function to query the database (custom/Extension/application/Ext/Utils/getMakers.php):
<?php
function getMakers() {
static $makers = null;
if (!$makers){
global $db;
$query = "SELECT id, name FROM a1_maker";
$result = $db->query($query, false);
$accounts = array();
$accounts[''] = '';
while (($row = $db->fetchByAssoc($result)) !=null) {
$accounts[$row['id']] = $row['name'];
}
}
return $makers;
}
?>
Then, I set 'function' field in Vardefs to point to the function (custom/Extension/modules/Maker/Ext/Vardefs/makers_template.php):
<?php
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'len' => '100',
'comment' => 'List of makers populated from the database',
);
?>
Unfortunately, there are no errors and the repair/rebuild runs fine. I am just unable to see the custom field when I go into studio. Can anyone please help point out what I may be doing wrong?
I would recommend checking existence of newly created field 'list_of_makers' in cache/modules/Maker/Makervardefs.php file. If new field definition exists in that file, try add 'studio' => 'visible' to custom/Extension/modules/Maker/Ext/Vardefs/makers_template.php to get something like this:
<?php
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'studio' => 'visible'
'len' => '100',
'comment' => 'List of makers populated from the database',
);
Try to edit your custom/modules/Maker/metadata/editviewdefs.php manually and insert field definition by hand in proper place if everything above won't work.
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'studio' => 'visible'
'len' => '100',
'comment' => 'List of makers populated from the database',
'studio' => array(
'listview' => true,
'detailview' => true,
'editview' => true
),
);

Use both comma and point separator

I have to modify a Zend form where some of the fields can contain decimals. Currently you can only enter your decimals using a point: 34.75)
What I'd like the users to be able is to write their decimals both with a comma or a point. The fields can contain either numbers like 34.75 and 34,75 (In this case, both have the same value). I don't want to modify any configuration on the server, so I need to do this in the code.
Right now the value of some fields is calculated in function of other fields; so when you enter a comma, it messes up the calculations. It's done in javascript, and I'll need to fix those calculations - but for now, I want to fix this issue in the php code when I retrieve the form.
I tried to find a solution on the Zend website, but I didn't find anything I've already read elsewhere with more examples. As you'll see in the code, I need to add either a filter or a validator to a zend_form_element_text. I cannot use a str_replace, as the element is a zend_form_element_text.
I have found this other question for reference.
Here is my resulting code:
$tabBilanFrais = array( 'txtFraisSecretariat' => array( 'nom' => 'Frais secrétariat', 'disabled' => true, "class"=>"calcul"),
'txtFraisRegion' => array( 'nom' => 'Frais région', 'disabled' => false),
'txtFraisSalle' => array( 'nom' => 'Salle', 'disabled' => false, "class"=>"calcul"),
'txtFraisPause' => array( 'nom' => 'Pauses', 'disabled' => false, "class"=>"calcul"),
'txtDivers' => array( 'nom' => 'Divers', 'disabled' => false, "class"=>"calcul"),
'txtTotalRegion' => array( 'nom' => 'Total région', 'disabled' => true, "class"=>"total"),
'txtIndemnisationAdherent' => array( 'nom' => 'Comm. ADH', 'disabled' => true, "class"=>"calcul"),
'txtIndemnisationPAP' => array( 'nom' => 'Comm. PAP', 'disabled' => true, "class"=>"calcul"),
'txtIndemnisationForNext' => array( 'nom' => 'Comm. ForNext', 'disabled' => true, "class"=>"calcul"),
'txtIndemnisationPROStages' => array( 'nom' => 'Comm. PROStages', 'disabled' => true, "class"=>"calcul"),
'txtRecettes' => array( 'nom' => 'Recettes', 'disabled' => true, "class"=>"totalMontant"),
'txtDepenses' => array( 'nom' => 'Dépenses', 'disabled' => true, "class"=>"totalMontant"),
'txtRecettesH' => array( 'nom' => 'Recettes', 'disabled' => false, "class"=>"hiddenTxt"),
'txtDepensesH' => array( 'nom' => 'Dépenses', 'disabled' => false, "class"=>"hiddenTxt")
);
$tabFormulaire = array() ;
foreach($tabBilanFrais as $id => $tabElement)
{
if($tabElement['nom'] == 'Frais region' )
$element = new Zend_Form_Element_Hidden($id, array("label" => $tabElement['nom'], "required" => false, 'decorators' => array("ViewHelper", "Errors", "Label"))) ;
else{
$element = new Zend_Form_Element_Text($id, array("label" => $tabElement['nom'], "required" => false, 'decorators' => array("ViewHelper", "Errors", "Label"))) ;
//$element->addFilter('pregReplace', array('match' => '/,/', 'replace' => '.'));
$element->addFilter('LocalizedToNormalized');
$element->addValidator('float', true, array('locale' => 'fr_FR'));
if(isset($tabElement['class']) && $tabElement['class']){
$element->setAttrib('class', $tabElement['class']);
}
}
if( $tabElement['disabled'])
$element->setAttrib('disabled', 'disabled');
$tabFormulaire[] = $element ;
}
The pregReplace isn't working. The validator is (comma becomes a .). I get an error message about the number not being a float.
You can always write your own validator. In case of float I faced the same problem like you:
class Yourlib_Validate_Float extends Zend_Validate_Abstract
{
const INVALID = 'floatInvalid';
const NOT_FLOAT = 'notFloat';
/**
* #var array
*/
protected $_messageTemplates = array(
self::INVALID => "Invalid type given. String, integer or float expected",
self::NOT_FLOAT => "'%value%' does not appear to be a float",
);
public function isValid($value)
{
$this->_setValue($value);
$value = str_replace(',', '.', $value);
if (!is_string($value) && !is_int($value) && !is_numeric($value)) {
$this->_error(self::INVALID);
return false;
}
if (is_numeric($value)) {
return true;
}
$this->_error(self::NOT_FLOAT);
return false;
}
}
And to add the validator:
$element->addValidator(new Yourlib_Validate_Float());
Please rename Yourlib to whatever suits you. And you need to register your "namespace" in the application.ini like this:
autoloadernamespaces.Yourlib = "Yourlib_"
Strictly speaking this validator is a numeric validator. It accepts all numeric values like ints and floats thru the check with is_numeric. Feel free to modify that.
Alright, here is the modified part of the code:
foreach($tabBilanFrais as $id => $tabElement)
{
if($tabElement['nom'] == 'Frais region' )
$element = new Zend_Form_Element_Hidden($id, array("label" => $tabElement['nom'], "required" => false, 'decorators' => array("ViewHelper", "Errors", "Label"))) ;
else{
$element = new Zend_Form_Element_Text($id, array("label" => $tabElement['nom'], "required" => false, 'decorators' => array("ViewHelper", "Errors", "Label"))) ;
$element->addFilter('pregReplace', array('match' => '/,/', 'replace' => '.'));
$element->addFilter('LocalizedToNormalized');
$element->addValidator(new Anper_Validate_Float(), true, array('locale' => 'fr_FR'));
if(isset($tabElement['class']) && $tabElement['class']){
$element->setAttrib('class', $tabElement['class']);
}
}
if( $tabElement['disabled'])
$element->setAttrib('disabled', 'disabled');
$tabFormulaire[] = $element ;
}
But now I need the values of the fields in $element to have the comma replaced by a point before the element is added to $tabFormulaire. Currently numbers with a comma are truncated (124,5 becomes 124) when I validate the form and display the updated values.
The pregreplace doesn't seem to work.
Edit: it seems I don't need the pregReplace. I used two echo in my isValid function for the custom validator: one before the str_replace and one after. When I write in one of the field a value with a comma, both the echo displays the number with a point. I assume it's the result of the filter LocalizedToNormalized.
What I don't understand is why once the values are saved and displayed those with a comma are truncated despite the findings I just made.
Edit2: If I write for example 124 8, and use a pregReplace to do like there was no blank, the 8 isn't kept on save; despite the pregReplace working (tried with my previous echo).
Although #bitWorking's answer is 100% OK, from the view point of semantics, it's better to use a filter (since it's more of filtering rather than validating)
either NumberFormat filter or writing your own.

Categories