CRUD generator yii2 error - php

I have error "syntax error, unexpected '}'" in yii2 CRUD generator. I created controller CountryController in basic/controllers path, model Country in basic/models path and folder country in views. I'm trying to make CRUD operation with parameters:
Model Class : app\models\Country
Search Model Class : app\models\CountrySearch
Controller Class : app\controllers\CountryController
View path : #app/views/country
and have error. I cant find solution in google and dont know what to do.
ERROR:
in W:\XAMPP\htdocs\basic\vendor\yiisoft\yii2-gii\generators\crud\default\views\_search.php at line 28
19202122232425262728293031323334353637
<div class="<?= Inflector::camel2id(StringHelper::basename($generator->modelClass)) ?>-search">
<?= "<?php " ?>$form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
<?php if ($generator->enablePjax)
?>'options' => [
'data-pjax' => 1
],<?php } >
]); ?>
<?php
$count = 0;
foreach ($generator->getColumnNames() as $attribute) {
if (++$count < 6) {
echo " <?= " . $generator->generateActiveSearchField($attribute) . " ?>\n\n";
} else {
echo " <?php // echo " . $generator->generateActiveSearchField($attribute) . " ?>\n\n";
2. yii\base\ErrorHandler::handleFatalError()
$_GET = [
'r' => 'gii/default/view',
'id' => 'crud',
];
$_POST = [
'_csrf' => 'ZFFUX0VCUjgAMhwAKDgwZ1UQFw8dexZPLwtlZhEMF2AJAh0ZEi8QFQ==',
'Generator' => [
'modelClass' => 'app\\models\\Country',
'searchModelClass' => 'app\\models\\CountrySearch',
'controllerClass' => 'app\\controllers\\CountryController',
'viewPath' => '#app/views/country',
'baseControllerClass' => 'yii\\web\\Controller',
'indexWidgetType' => 'grid',
'enableI18N' => '0',
'enablePjax' => '0',
'messageCategory' => 'app',
'template' => 'default',
],
'preview' => '',
];
$_COOKIE = [
'Phpstorm-b0412478' => '63e8918e-ac29-43de-9816-571b71512aad',
'_csrf' => 'e3a51f05887c990dee11a82408437a3e87c4de7d372dba216a0834374d5b602ca:2:{i:0;s:5:"_csrf";i:1;s:32:"dcH_mzb_1ACPX9DwKZ19TNEXmSIFWmB-";}',
'PHPSESSID' => '2a91078gc1nh6q5br71p0hkuu6',
'_identity' => '8142bf058f7de9bda458b829902ac7db3b69c135c0c908aaaefe8bf2105e8d62a:2:{i:0;s:9:"_identity";i:1;s:28:"["100","test100key",2592000]";}',
];

You close if condition ,where it is open,try below one
<?= "<?php " ?>$form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
<?php if ($generator->enablePjax) {
?>'options' => [
'data-pjax' => 1
],<?php } >
]); ?>

Related

Drupal 8 Custom Module - From dynamic data (API) to store at Fields (Content type) Drupal DB

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();

PHP include another file, loop over array and run function for each record

I would like to access the values of an array in another php file ... loop over it and run a function over each record. I can't seem to access the values though ... I'm getting an internal error. How to properly do this? That's my setup:
contacts.php
<?php
$contacts_de = array(
'name01' => array(
'firstName' => 'FirstName01',
'lastName' => 'LastName01',
'gender' => 'm',
'language' => 'de',
'email' => 'email01'
),
'name02' => array(
'firstName' => 'FirstName02',
'lastName' => 'LastName02',
'gender' => 'f',
'language' => 'de',
'email' => 'email02'
)
);
mail.php
<?php
include('contacts.php');
function renderContacts($arr) {
global $lang,$contacts_de;
$d = '';
foreach($arr as $i) {
if ($i['gender'] == 'm') {
.$d = 'Mr. '.$i['firstName'].' '.$i['lastName']
} else if ($i['gender'] == 'm') {
.$d = 'Ms. '.$i['firstName'].' '.$i['lastName']
}
}
echo $d;
}
renderContacts();
default.js
$('#sendbtn').on('click', function() {
$.ajax({
type: "POST",url: '/mail.php',
success: function(response,textStatus,jqXHR) {
console.log(response);
},
error: function (jqXHR, status, err) {
console.log(err);
}
});
});
Desired Console.log
Mr. FirstName01 LastName01
Ms. FirstName02 LastName02
The simple answer to what you're asking is:
<?php # contacts.php
$contacts = array(
'name01' => array(
'firstName' => 'FirstName01',
'lastName' => 'LastName01',
'gender' => 'm',
'language' => 'de',
'email' => 'email01'
),
'name02' => array(
'firstName' => 'FirstName02',
'lastName' => 'LastName02',
'gender' => 'f',
'language' => 'de',
'email' => 'email02'
)
);
and
<?php # whatever.php
require __DIR__ . '/contacts.php';
function render_contacts(array $contacts) {
foreach ($contacts as $contact) {
$prefix = $contact['gender'] == 'm' ? 'Mr' : 'Ms';
printf("%s. %s %s\n", $prefix, $contact['firstName'], $contact['lastName']);
}
}
render_contacts($contacts);
A non-separated sandbox can be seen here: http://sandbox.onlinephpfunctions.com/code/6daa0147671fcaac9c51fe919c4a8f916181fad1
I've also cleaned up your code a little bit for you, removing things like the global keyword, some syntax errors, and the JavaScript you linked, as it's irrelevant to the issue.
GL.

Codeigniter call one's Class method inside another Classe's method

To be very specific - there is CRM system written in Codeigniter called Rise. I would like to make (automatically) an expense entry ( call save() method of an Expenses class ) each time someone logs in ( inside save_timelog() method of a Projects class ) time manually.
Expense Controller:
function save() {
validate_submitted_data(array(
"id" => "numeric",
"expense_date" => "required",
"category_id" => "required",
"amount" => "required"
));
$id = $this->input->post('id');
$target_path = get_setting("timeline_file_path");
$files_data = move_files_from_temp_dir_to_permanent_dir($target_path, "expense");
$has_new_files = count(unserialize($files_data));
$data = array(
"expense_date" => $this->input->post('expense_date'),
"title" => $this->input->post('title'),
"description" => $this->input->post('description'),
"category_id" => $this->input->post('category_id'),
"amount" => unformat_currency($this->input->post('amount')),
"project_id" => $this->input->post('expense_project_id'),
"user_id" => $this->input->post('expense_user_id'),
"files" => $files_data
);
<.. ETC. CHECKING FILES ..>
$save_id = $this->Expenses_model->save($data, $id);
if ($save_id) {
echo json_encode(array("success" => true, "data" => $this->_row_data($save_id), 'id' => $save_id, 'message' => lang('record_saved')));
} else {
echo json_encode(array("success" => false, 'message' => lang('error_occurred')));
}
}
Projects Controller:
function save_timelog() {
$this->access_only_team_members();
$id = $this->input->post('id');
$start_time = $this->input->post('start_time');
$end_time = $this->input->post('end_time');
$note = $this->input->post("note");
$task_id = $this->input->post("task_id");
if (get_setting("time_format") != "24_hours") {
$start_time = convert_time_to_24hours_format($start_time);
$end_time = convert_time_to_24hours_format($end_time);
}
$start_date_time = $this->input->post('start_date') . " " . $start_time;
$end_date_time = $this->input->post('end_date') . " " . $end_time;
$start_date_time = convert_date_local_to_utc($start_date_time);
$end_date_time = convert_date_local_to_utc($end_date_time);
$data = array(
"project_id" => $this->input->post('project_id'),
"start_time" => $start_date_time,
"end_time" => $end_date_time,
"note" => $note ? $note : "",
"task_id" => $task_id ? $task_id : 0,
);
if (!$id) {
//insert mode
$data["user_id"] = $this->input->post('user_id') ? $this->input->post('user_id') : $this->login_user->id;
} else {
//edit mode
//check edit permission
$this->check_timelog_updte_permission($id);
}
$save_id = $this->Timesheets_model->save($data, $id);
if ($save_id) {
echo json_encode(array("success" => true, "data" => $this->_timesheet_row_data($save_id), 'id' => $save_id, 'message' => lang('record_saved')));
} else {
echo json_encode(array("success" => false, 'message' => lang('error_occurred')));
}
}
So now what I'm trying to do is inside Projects controller, save_timelog() method just below these lines:
<...>
if (!$id) {
//insert mode
$data["user_id"] = $this->input->post('user_id') ? $this->input->post('user_id') : $this->login_user->id;
} else {
//edit mode
//check edit permission
$this->check_timelog_updte_permission($id);
}
/* CREATING A SAMPLE ARRAY WITH STATIC DATA FOR AN EXAMPLE EXPENSE ENTRY */
$a = array(
"expense_date" => '2018-03-13',
"title" => 'Cat Food',
"description" => 'Sheba, Felix, KiteKat',
"category_id" => '85',
"amount" => '500',
"project_id" => '84',
"user_id" => '10',
"files" => $files_data
);
/* TRYING TO SAVE/SEND EXAMPLE ARRAY TO Expenses Class save() method (?) */
$b = $this->Expenses_model->save($a);
/* RESULT (?) */
$save_id = $this->Timesheets_model->save($data, $id);
if ($save_id) {
echo json_encode(
array(
array(
"success" => true,
"data" => $this->_timesheet_row_data($save_id),
'id' => $save_id,
'message' => lang('record_saved')
),
array(
"success" => true,
"data" => _row_data($b),
'id' => $save_id,
'message' => lang('record_saved')
)
)
);
} else {
echo json_encode(array("success" => false, 'message' => lang('error_occurred')));
}
<.. Closing save_timelog() method ..>
However it surely doesn't work and all I get is "POST http://rise.test/index.php/projects/save_timelog 500 (Internal Server Error)".
I also load Expenses model and Expenses categories model in Projects _construct():
Projects Controller:
public function __construct() {
parent::__construct();
$this->load->model("Project_settings_model");
$this->load->model("Expense_categories_model");
$this->load->model("Expenses_model");
}
I also contacted developers of Rise with following question/answer:
Me:
In Projects controller save_timelog() method I just want to call
Expenses controller save() method, and if save_timelog() is successful
I would like to save an Expense ( $this->Expenses_model->save($data,
$id); ) with appropriate data. Could be static values for now for
$data array in save() method - just to find out it's working.
Rise Devs:
Hi, You are doing almost right. Just remove the 2nd parameter $id. It
should be used only for update. $this->Expenses_model->save($data)
Would really appreciate any help and directions! Thanks.

Symfony 1.4 form checkbox array to string conversation

I have following error during creating checboxes in Symfony 1.4 app.
Checkboxes are rendered but with "Array to string conversation" error.
Below is my code.
Form
$this->setWidget('emails', new sfWidgetFormChoice([
'label' => 'Emails',
'expanded' => true,
'multiple' => true,
'choices' => array('test', 'test2'),
]));
Render
<div class="container emails">
<fieldset>
<legend>
<?php echo $form['emails']->renderLabel(); ?>
</legend>
<?php echo $form['emails']->render(); ?>
<?php echo $form['emails']->renderError(); ?>
</fieldset>
</div>
Error
Notice: Array to string conversion in /var/www/html/symfony/1_4_1/lib/widget/sfWidgetFormSelectCheckbox.class.php on line 103
Notice: Array to string conversion in /var/www/html/symfony/1_4_1/lib/widget/sfWidgetFormSelectCheckbox.class.php on line 10
My Php version is 5.5.8
Symfony version 1.4.19
I know that the best way would be move app to newest symfony version, but this application is too large to rewrite.
Anyone have idea how to solve it?
//Edit
I noticed that if I change code to
$arr = [];
array_push($arr, 'test');
array_push($arr, 'test2');
$this->setWidget('emails', new sfWidgetFormSelectCheckbox([
'label' => __('Adresy email'),
'choices' =>$arr,
]));
it returns any errors, but if I add one more value to array, errors shows again.
Whole class code
class EmailFooterGeneratorForm extends BaseForm
{
/**
* configure...
*
* #param mixed $data
*/
public function configure()
{
sfContext::getInstance()->getConfiguration()->loadHelpers('I18N');
$this->setWidget('regards', new sfWidgetFormInputText([
'label' => __('Treść pozdrowień'),
'default' => 'Pozdrowienia/Best regards',
], [
'size' => 45
]));
$this->setWidget('emails', new sfWidgetFormChoice([
'label' => __('Adresy email'),
'choices' => $this->getDefault('phones'),
]));
$this->setWidget('phones', new sfWidgetFormChoice([
'label' => __('Numery telefonu'),
'expanded' => true,
'multiple' => true,
'choices' => $this->getDefault('phones'),
]));
$this->setWidget('employment', new sfWidgetFormSelectRadio([
'label' => __('Zatrudnienie'),
'choices' => $this->buildEmployment($this->getDefault('employment'))
]));
$this->setWidget('certyfications', new sfWidgetFormChoice([
'label' => __('Certyfikaty'),
'multiple' => true,
'expanded' => true,
'choices' => ['AEO', 'TÜV Rheinland', 'FSC']
]));
$templateChoices = [
'' . __('Szablon') . ' 1 ',
'' . __('Szablon') . ' 2 '
];
$this->setWidget('templates', new sfWidgetFormSelectRadio([
'label' => __('Szablony'),
'choices' => $templateChoices
]));
$this->setWidget('www', new sfWidgetFormInputText([
'label' => __('Strona wwww'),
'default' => 'www.fakro.com'
]));
$this->setValidators([
'regards' => new sfValidatorString(
['max_length' => 50, 'min_length' => 12],
['required' => __('Wymagane'),
'min_length' => __('Treść pozdrowień musi mieć przynajmniej %min_length% znaków.'),
'max_length' => __('Treść pozdrowień może mieć maksymalnie %max_length% znaków.')
]
),
'emails' => new sfValidatorChoice(
['choices' => array_keys($this->getDefault('emails')), 'multiple' => true],
['required' => __('Wymagane')]
),
'employment' => new sfValidatorChoice(
['choices' => array_keys($this->getDefault('employment'))],
['required' => __('Wymagane')]
),
'templates' => new sfValidatorChoice(
['choices' => array_keys($templateChoices)],
['required' => __('Wymagane')]
),
'www' => new sfValidatorRegex(
['pattern' => '/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/'],
['invalid' => __('Niepoprawny adres strony wwww')]
)
]);
$this->validatorSchema['phones'] = new sfValidatorString(['required' => false]);
$this->validatorSchema['certyfications'] = new sfValidatorString(['required' => false]);
}
private function buildEmployment($employment)
{
$arr = [];
foreach ($employment as $key) {
$str =
"<div style='margin-left: 30px'>" .
__('Firma') . ": " . $key['company_name'] . "<br>" .
__('NIP') . ": " . $key['nip'] . "<br>" .
__('REGON') . ": " . $key['regon'] . "<br>" .
__('Miasto') . ": " . $key['city'] . "<br>" .
__('Ulica') . ": " . $key['street'] . "<br>" .
__('Kod') . ": " . $key['postal'] . "<br>" .
__('Kraj') . ": " . $key['country'] . "<br>" .
__('Wydział') . ": " . $key['depertment_name'] . "<br>" .
__('Stanowisko') . ": " . $key['job_name'] . "<br>
</div>"
;
$arr[] = $str;
}
return $arr;
}
}
It is a bit late, but since I was having this issue and someone else may need it, I found that the issue was that I was using a sfWidgetFormChoice set to be multiple, but I didn't tell it to the validator.
The solution is just to pass the option to it as well.
End up having something like
$this->validatorSchema['choices_name'] = new sfValidatorChoice([
'required' => false,
'multiple' => true,
'choices' => $choices
]);
I'm using it in a Form class, that's why you see $this->validatorSchema, if you are using it anywhere else, like in the OP case, just add that 'multiple' => true as option in the options array.

Yii webcam extension

In Yii,Iam using yii-jpegcam webcam extension used for taking photos in my application and it works fine with the following url format
index.php?r=user/newphoto
But my application is in "/" format (index.php/user/newphoto). So this extension not working with my url format. How it can be solved?
Extension Link used : http://www.yiiframew...on/yii-jpegcam/
http://www.yiiframework.com/extension/yii-jpegcam/
And my view code is :
<?php $onBeforeSnap = "document.getElementById('upload_results').innerHTML = '<h1>Uploading...</h1>';";
$completionHandler = <<<BLOCK
if (msg == 'OK') {
document.getElementById('upload_results').innerHTML = '<h1>OK! ...redirecting in 3 seconds</h1>';
// reset camera for another shot
webcam.reset();
setTimeout(function(){window.location = "index.php?r=user/index";},3000);
}
else alert("PHP Error: " + msg);
BLOCK;
$this->widget('application.extensions.jpegcam.EJpegcam', array(
'apiUrl' => 'index.php?r=user/jpegcam.saveJpg',
'shutterSound' => false,
'stealth' => true,
'buttons' => array(
'configure' => 'Configure',
'takesnapshot' => 'Take Snapshot!'
),
'onBeforeSnap' => $onBeforeSnap,
'completionHandler' => $completionHandler
)); ?>
If urlManager enabled in config, you should change apiUrl value with createUrl method :
$this->widget('application.extensions.jpegcam.EJpegcam', array(
'apiUrl' => Yii::app()->urlManager->createUrl('index.php/user/jpegcam.saveJpg'),
'shutterSound' => false,
'stealth' => true,
'buttons' => array(
'configure' => 'Configure',
'takesnapshot' => 'Take Snapshot!'
),
'onBeforeSnap' => $onBeforeSnap,
'completionHandler' => $completionHandler
));

Categories