Kohana ORM Model not loading - kohana

In the following code, the "add" action works as expected, but the remove action throws an error citing that Kohana "Cannot delete favorites model because it is not loaded."
Any ideas?
if ($_GET['action'] == 'add')
{
$favorites = ORM::factory('favorites');
$favorites->question_id = $_GET['question_id'];
$favorites->user_id = Kohana_Facebook::instance()->user_id();
$favorites->save();
}
elseif ($_GET['action'] == 'remove')
{
$favorites = ORM::factory('favorites')
->where('user_id', '=', $facebook->user_id())
->and_where('question_id', '=', $_GET['question_id'])
->find();
$favorites->delete();
}
A var_dump($favorites) show this:
object(Model_Favorites)#24 (31) {
["_table_name:protected"]=> string(9) "favorites"
["_has_one:protected"]=> array(0) { }
["_belongs_to:protected"]=> array(0) { }
["_has_many:protected"]=> array(0) { }
["_load_with:protected"]=> array(0) { }
["_validation:protected"]=> NULL
["_object:protected"]=> array(2) { ["user_id"]=> string(8) "60717257" ["question_id"]=> string(1) "2" }
["_changed:protected"]=> array(0) { }
["_related:protected"]=> array(0) { }
["_valid:protected"]=> bool(false)
["_loaded:protected"]=> bool(false)
["_saved:protected"]=> bool(false)
["_sorting:protected"]=> NULL
["_foreign_key_suffix:protected"]=> string(3) "_id"
["_object_name:protected"]=> string(9) "favorites"
["_object_plural:protected"]=> string(11) "favoriteses"
["_table_columns:protected"]=> array(2) { ["user_id"]=> array(13) { ["type"]=> string(3) "int" ["min"]=> string(11) "-2147483648" ["max"]=> string(10) "2147483647" ["column_name"]=> string(7) "user_id"
["column_default"]=> NULL
["data_type"]=> string(3) "int"
["is_nullable"]=> bool(false)
["ordinal_position"]=> int(1)
["display"]=> string(2) "11"
["comment"]=> string(0) ""
["extra"]=> string(0) ""
["key"]=> string(3) "PRI"
["privileges"]=> string(31) "select,insert,update,references" }
["question_id"]=> array(13) { ["type"]=> string(3) "int" ["min"]=> string(11) "-2147483648" ["max"]=> string(10) "2147483647" ["column_name"]=> string(11) "question_id" ["column_default"]=> NULL ["data_type"]=> string(3) "int" ["is_nullable"]=> bool(false) ["ordinal_position"]=> int(2) ["display"]=> string(2) "11" ["comment"]=> string(0) "" ["extra"]=> string(0) "" ["key"]=> string(3) "PRI" ["privileges"]=> string(31) "select,insert,update,references" } } ["_updated_column:protected"]=> NULL ["_created_column:protected"]=> NULL ["_primary_key:protected"]=> string(2) "id" ["_primary_key_value:protected"]=> NULL ["_table_names_plural:protected"]=> bool(true) ["_reload_on_wakeup:protected"]=> bool(true) ["_db:protected"]=> object(Database_MySQL)#23 (6) { ["_connection_id:protected"]=> string(40) "f9eb0f07846bef120d6d8414616f81f993f5306a" ["_identifier:protected"]=> string(1) "`" ["last_query"]=> string(98) "SELECT `favorites`.* FROM `favorites` WHERE `user_id` = '60717257' AND `question_id` = '2' LIMIT 1" ["_instance:protected"]=> string(7) "default" ["_connection:protected"]=> resource(73) of type (mysql link) ["_config:protected"]=> array(6) { ["type"]=> string(5) "mysql" ["connection"]=> array(3) { ["hostname"]=> string(9) "localhost" ["database"]=> string(17) "davekiss_dumbpoll" ["persistent"]=> bool(false) } ["table_prefix"]=> string(0) "" ["charset"]=> string(4) "utf8" ["caching"]=> bool(false) ["profiling"]=> bool(true) } }
["_db_group:protected"]=> NULL
["_db_applied:protected"]=> array(0) { }
["_db_pending:protected"]=> array(0) { }
["_db_reset:protected"]=> bool(true)
["_db_builder:protected"]=> NULL
["_with_applied:protected"]=> array(0) { }
["_cast_data:protected"]=> array(0) { } }

Yes, it is not loaded in your code.
You need to add find() before your delete()
UPD:
As I can see - it is just a relation tables without single PK field (id)
You could delete row with something like:
DB::delete('favorites')->where('user_id', '=', $facebook->user_id())
->and_where('question_id', '=', $_GET['question_id'])
->execute(Database::instance());
Or you could use remove() method (since seems like you're using kohana ORM relations)

Face same issue and fixed with the solution
add code like
protected $_primary_key = 'your tables primary key';

I have the same issue after loading my codes with ->where() and ->find()
Just make sure that the
protected $_primary_key = 'id';
is defined at the model.

Related

Script that converts a string to a date, compares this date to today's date and counts this date if it is earlier

I work for a company that makes web portals for libraries.
Today, I work mainly with subscriber data.
Here is some of subscriber data:
array(9) {
["id"]=>
string(19) "8235798454376842909"
["username"]=>
string(12) "Test xxxx"
["login"]=>
string(11) "xxxx"
["role"]=>
string(5) "guest"
["account"]=>
string(4) "opac"
["details"]=>
array(27) {
["lastname"]=>
string(7) "xxxx"
["firstname"]=>
string(4) "Test"
["subscriptions"]=>
array(1) {
[0]=>
array(12) {
["subscription"]=>
array(17) {
["ruleSetsLateLoan"]=>
array(1) {
[0]=>
array(3) {
["id"]=>
string(19) "6661733132890635183"
["name"]=>
string(16) "Tous docs retard"
["deleted"]=>
bool(false)
}
}
}
["endDate"]=>
string(10) "06-05-2022"
["startDate"]=>
string(10) "06-05-2021"
}
}
["loans"]=>
array(1) {
[0]=>
array(17) {
["objectType"]=>
string(9) "User\Loan"
["id"]=>
string(19) "7348367352886005629"
["startDate"]=>
string(10) "20-10-2021"
["endDate"]=>
string(10) "10-11-2021"
["returnDate"]=>
NULL
["returnLibrary"]=>
string(22) "Bibliothèque Brassens"
["extendable"]=>
bool(true)
["nonExtendabilityReason"]=>
NULL
["bibrecordId"]=>
string(18) "224787138527266506"
["bibrecordTitle"]=>
string(33) "La jeune fille et la nuit : roman"
["bibrecordResponsibles"]=>
string(15) "Guillaume Musso"
["bibrecordEditor"]=>
string(13) "Calmann-Lévy"
["bibrecordPublishedDate"]=>
NULL
["isElectronical"]=>
bool(false)
["bibrecordCode"]=>
string(13) "9782702163634"
["bibrecordType"]=>
string(5) "Texte"
["late"]=>
bool(true)
}
}
["subenddate"]=>
string(10) "06-05-2022"
}
}
From these, I would like:
Know if there are overdue loans
If yes, how much?
As you can see from the loans data:
startDate
endDate (it is especially this one that interests me)
are strings
I call on your expertise because I would like to set up a script with Twig variables which:
convert the loan > endDate string into a date
compare this date to today's date
if the endDate is prior to today's date, count it (because it means that the subscriber has an overdue loan)
(finally) retrieve this number, this result
I appeal to you because my knowledge is limited to HTML/CSS and 2-3 Twig functions.
By searching on the Internet, I should be able to do the first 2 actions (convert the string of characters from loan > endDate to a date and compare this date to the current date), but since each action takes the result of the previous one... I don't know how to do
Can you help me please ?
In advance, thank you for your help
Have a nice day
Here is the data relating to the subscriber's loans:
["loans"]=>
array(4) {
[0]=>
array(17) {
["objectType"]=>
string(9) "User\Loan"
["id"]=>
string(19) "1030181343798038358"
["startDate"]=>
string(10) "24-08-2022"
["endDate"]=>
string(10) "26-08-2022"
["returnDate"]=>
NULL
["returnLibrary"]=>
string(22) "Bibliothèque Cendrars"
["extendable"]=>
bool(true)
["nonExtendabilityReason"]=>
NULL
["bibrecordId"]=>
string(19) "8412379444127231486"
["bibrecordTitle"]=>
string(22) "Monika. ; Jeux d'été"
["bibrecordResponsibles"]=>
string(14) "Ingmar Bergman"
["bibrecordEditor"]=>
string(7) "Opening"
["bibrecordPublishedDate"]=>
string(4) "2001"
["isElectronical"]=>
bool(false)
["bibrecordCode"]=>
string(0) ""
["bibrecordType"]=>
string(23) "Ressource électronique"
["late"]=>
bool(true)
}
[1]=>
array(17) {
["objectType"]=>
string(9) "User\Loan"
["id"]=>
string(19) "1671289858474018264"
["startDate"]=>
string(10) "29-06-2021"
["endDate"]=>
string(10) "20-07-2021"
["returnDate"]=>
NULL
["returnLibrary"]=>
string(22) "Bibliothèque Cendrars"
["extendable"]=>
bool(true)
["nonExtendabilityReason"]=>
NULL
["bibrecordId"]=>
string(19) "9064740467286336344"
["bibrecordTitle"]=>
string(22) "Le château des pianos"
["bibrecordResponsibles"]=>
string(31) "Pierre Créac'h, textes & comp."
["bibrecordEditor"]=>
string(13) "Ed. Sarbacane"
["bibrecordPublishedDate"]=>
string(4) "2014"
["isElectronical"]=>
bool(false)
["bibrecordCode"]=>
string(13) "9782848657066"
["bibrecordType"]=>
string(5) "Texte"
["late"]=>
bool(true)
}
[2]=>
array(17) {
["objectType"]=>
string(9) "User\Loan"
["id"]=>
string(19) "2671623005489329067"
["startDate"]=>
string(10) "29-06-2021"
["endDate"]=>
string(10) "28-07-2023"
["returnDate"]=>
NULL
["returnLibrary"]=>
string(20) "Médiathèque Aragon"
["extendable"]=>
bool(true)
["nonExtendabilityReason"]=>
NULL
["bibrecordId"]=>
string(19) "5404768465078117954"
["bibrecordTitle"]=>
string(37) "Château l'attente : Addendum (2 / 2)"
["bibrecordResponsibles"]=>
string(12) "Linda Medley"
["bibrecordEditor"]=>
string(8) "Delcourt"
["bibrecordPublishedDate"]=>
string(4) "2013"
["isElectronical"]=>
bool(false)
["bibrecordCode"]=>
string(13) "9782756039985"
["bibrecordType"]=>
string(5) "Texte"
["late"]=>
bool(false)
}
[3]=>
array(17) {
["objectType"]=>
string(9) "User\Loan"
["id"]=>
string(19) "6187422550922662455"
["startDate"]=>
string(10) "24-08-2022"
["endDate"]=>
string(10) "26-08-2022"
["returnDate"]=>
NULL
["returnLibrary"]=>
string(22) "Bibliothèque Cendrars"
["extendable"]=>
bool(true)
["nonExtendabilityReason"]=>
NULL
["bibrecordId"]=>
string(19) "2571403561722263349"
["bibrecordTitle"]=>
string(39) "Une Étude en rouge -- livre numérique"
["bibrecordResponsibles"]=>
string(20) " Doyle, Arthur Conan"
["bibrecordEditor"]=>
string(0) ""
["bibrecordPublishedDate"]=>
NULL
["isElectronical"]=>
bool(false)
["bibrecordCode"]=>
string(0) ""
["bibrecordType"]=>
string(23) "Ressource électronique"
["late"]=>
bool(true)
}
}
If you look at ["late"], there is a boolean test on each document to know if it is late or not.
How to count the number of true booleans in an array? Knowing that in the example above, the answer is 3 (out of 4 loans)

I can't show my inventory on my reports in Amazon Selling Partner API

object(ClouSale\AmazonSellingPartnerAPI\Models\Reports\GetReportResponse)#482 (1) { ["container":protected]=> array(2) { ["payload"]=> object(ClouSale\AmazonSellingPartnerAPI\Models\Reports\Report)#491 (1) { ["container":protected]=> array(11) { ["marketplace_ids"]=> array(1) { [0]=> string(14) "A1VC38T7YXB528" } ["report_id"]=> string(11) "55933018913" ["report_type"]=> string(30) "GET_MERCHANT_LISTINGS_ALL_DATA" ["data_start_time"]=> object(DateTime)#506 (3) { ["date"]=> string(26) "2021-10-13 04:42:10.000000" ["timezone_type"]=> int(1) ["timezone"]=> string(6) "+00:00" } ["data_end_time"]=> object(DateTime)#483 (3) { ["date"]=> string(26) "2021-10-13 04:42:10.000000" ["timezone_type"]=> int(1) ["timezone"]=> string(6) "+00:00" } ["report_schedule_id"]=> NULL ["created_time"]=> object(DateTime)#502 (3) { ["date"]=> string(26) "2021-10-13 04:42:10.000000" ["timezone_type"]=> int(1) ["timezone"]=> string(6) "+00:00" } ["processing_status"]=> string(4) "DONE" ["processing_start_time"]=> object(DateTime)#481 (3) { ["date"]=> string(26) "2021-10-13 04:42:16.000000" ["timezone_type"]=> int(1) ["timezone"]=> string(6) "+00:00" } ["processing_end_time"]=> object(DateTime)#480 (3) { ["date"]=> string(26) "2021-10-13 04:42:25.000000" ["timezone_type"]=> int(1) ["timezone"]=> string(6) "+00:00" } ["report_document_id"]=> string(73) "amzn1.spdoc.1.3.2149a182-4354-4177-b03e-0bc4552cb190.T25GAW47NVJ50Z.47700" } } ["errors"]=> NULL } }
I want to show my inventory using Amazon Selling Partner API. Firstly, I created a report for this. I have report id, document id etc.
When I pull the report with using GetReports function using this information, the inventory does not appear. Is it normal?
my expectation was that
I solved my problem.
Firstly, If you want to see second image (my expectation) you have to need the document id.
So
Create a report and get a report ID
Get a documentID with using a reportID
Use getReportDocument function with using documentID
Open decrypto document and read file
This is my code (on laravel)
public function getInventoryReportData() {
header('Content-Type: text/html; charset=utf-8');
$options = [
'refresh_token' => self::constOptions["amazon"]["refresh_token"],
'client_id' => self::constOptions["amazon"]["client_id"],
'client_secret' => self::constOptions["amazon"]["client_secret"],
'region' => \ClouSale\AmazonSellingPartnerAPI\SellingPartnerRegion::$FAR_EAST,
'access_key' => self::constOptions["amazon"]["access_key"],
'secret_key' => self::constOptions["amazon"]["secret_key"],
'endpoint' => \ClouSale\AmazonSellingPartnerAPI\SellingPartnerEndpoint::$FAR_EAST,
'role_arn' => self::constOptions["amazon"]["role_arn"],
];
$accessToken = \ClouSale\AmazonSellingPartnerAPI\SellingPartnerOAuth::getAccessTokenFromRefreshToken(
$options['refresh_token'],
$options['client_id'],
$options['client_secret']
);
$config = \ClouSale\AmazonSellingPartnerAPI\Configuration::getDefaultConfiguration();
$config->setHost($options['endpoint']);
$config->setAccessToken($accessToken);
$config->setAccessKey($options['access_key']);
$config->setSecretKey($options['secret_key']);
$config->setRegion($options['region']);
$apiInstance = new \ClouSale\AmazonSellingPartnerAPI\Api\ReportsApi($config);
$report_document_id = "YOUR_DOCUMENT_ID_IN_HERE";
try {
$result = $apiInstance->getReportDocument($report_document_id);
$key = base64_decode($result->getPayload()->getEncryptionDetails()->getKey());
$iv = base64_decode($result->getPayload()->getEncryptionDetails()->getInitializationVector());
$decryptedData = openssl_decrypt(file_get_contents($result->getPayload()->getUrl()), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
$convertEncodeData = mb_convert_encoding($decryptedData, 'UTF-8', 'ASCII, JIS, UTF-8, SJIS');
echo $convertEncodeData;
} catch (Exception $e) {
echo 'Exception when calling ReportsApi->getReportDocument: ', $e->getMessage(), PHP_EOL;
}
}

How get object from indices in Areablock?

I have Pimcore\Model\Document\Tag\Areablock with tree elements table of indices:
array(3) {
[0]=>
array(2) {
["key"]=>
string(1) "3"
["type"]=>
string(8) "newsData"
}
[1]=>
array(2) {
["key"]=>
string(1) "1"
["type"]=>
string(7) "wysiwyg"
}
[2]=>
array(2) {
["key"]=>
string(1) "2"
["type"]=>
string(12) "videogallery"
}
}
How could I get newsData object from Areablock object?
I coudn't find function in Areablock for that and don't know how to get date.
Thanks in advance.
Areabricks are not subelements of the actual areablock, but are direct elements of current document. Their names are just differently constructed.
$areablock = $this->areablock("yourAreablock");
foreach ($areablock->getData() as $brick) {
if ($brick["type"] == "yourAreaBrickName") {
$nameOfTheEditableInBrick = "bigtitle";
$indexOfTheAreaBrick = $brick["key"];
// This is your element
$subelement = $this->document->getElement($nameOfTheEditableInBrick . $areablock->getName() . $brick["key"]);
}
}

Groovy MarkupBuilder passing string by reference

Doing transformation of a JSON feed to a format that can be consumed by our Endeca Instance, and settled on writing this transformation in Groovy, due to tools like JsonSlurper and MarkupBuilder. Our JSON feed input looks like this (saved as stage/newObject.json):
[
{
"Name": "Object Name",
"DimID": 0000,
"ObjectID": "Object-0000",
"TypeID": 1,
"Type": "Object Type",
"Description": "A Description",
"DirectorID": "007",
"DirectorName": "Bond, James",
"ParentObjectID": null,
"ObjectLevelID": 1,
"ObjectLevel": "MI-6",
"ProjectNumbers": [
"0001",
"0002"
],
"ManagerIDs": [
"001"
],
"ManagerNames": [
"M"
],
"SubObjectIDs": [
"006",
"005"
],
"TaskNumbers": [
"001"
],
"ProjectNames": [
"Casino Royal",
"Goldfinger",
"License to Kill"
]
}
]
And the code I've got to do the transform is this:
def rawJSONFile = new File("stage/newObject.json")
JsonSlurper slurper = new JsonSlurper()
def slurpedJSON = slurper.parseText(rawJSONFile.text)
def xmlOutput = new MarkupBuilder(new FileWriter(new File("stage/ProcessedOutput.xml")))
xmlOutput.RECORDS() {
for (object in slurpedJSON) {
RECORD() {
for (field in object) {
if (field.value != null) {
if (field.value.value.class.equals(java.util.ArrayList)) {
if (field.value.value.size > 0) {
for (subField in field.value.value) {
if (subField != null) {
PROP(NAME: field.key) {
PVAL(subField)
}
}
}
}
} else {
PROP(NAME: field.key) {
PVAL(field.value)
}
}
}
}
}
}
}
The issue we're experiencing is about half way down the groovy script, where it's dealing with sub fields (that is the arrays within the JSON), the closure that's creating the "PVAL" node is passing the subField variable by reference and it's not being treated as a string but a character array, so trying to do the output, we get a Memory location, rather than a String. The workaround we've got so far is this, but I wanted to know if there was a more elegant solution:
for (subField in field.value.value) {
if (subField != null) {
PROP(NAME: field.key) {
StringBuilder subFieldValue = new StringBuilder();
for(int i =0; i<subField.length; i++){
subFieldValue.append(subField[i])
}
PVAL(subFieldValue.toString())
}
}
}
Change subField in field.value.value to subField in field.value in
for (subField in field.value) {
if (subField != null) {
PROP(NAME: field.key) {
PVAL(subField)
}
}
}
Although this logic can be simplified as
xmlOutput.RECORDS {
slurpedJSON.each { map ->
Record {
map.each { k, v ->
if ( v in ArrayList ) {
v.each { val ->
PROP(NAME: k) {
PVAL(val)
}
}
} else {
PROP(NAME: k) {
PVAL(v)
}
}
}
}
}
}

Drupal Pressflow problem with hook_block

i'm having troubles with implementing the hook_block hook in a clean Pressflow installation. For some reason it always outputs ArrayArray for all my blocks. The reason for this is that the $info variable in the theme function is set to:
["block"]=>
array(7) {
["function"]=>
string(10) "fwtb_block"
["include files"]=>
array(0) {
}
["type"]=>
string(12) "theme_engine"
["theme path"]=>
string(21) "sites/all/themes/fwtb"
["arguments"]=>
array(1) {
["block"]=>
NULL
}
["theme paths"]=>
array(2) {
[0]=>
string(14) "modules/system"
[1]=>
string(21) "sites/all/themes/fwtb"
}
["preprocess functions"]=>
array(2) {
[0]=>
string(19) "template_preprocess"
[1]=>
string(25) "template_preprocess_block"
}
}
as you can see this is overwritten with my custom hook_block method. So now it thinks blocks should be rendered using my fwtb_block method which returns an array containing the subject and the content. That's why it prints ArrayArray. Any idea what is going wrong here?
This is my hook_block implementation:
function fwtb_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
$blocks['sidebar_description'] = array(
'info' => t('Sidebar description'),
'cache' => BLOCK_CACHE_GLOBAL,
'status' => TRUE,
'region' => 'left',
'visibility' => 0,
'custom' => FALSE
);
return $blocks;
case 'configure':
$form = array();
return $form;
case 'save':
return;
case 'view': default:
switch ($delta) {
case 'sidebar_description':
$block['subject'] = t('block_subject');
$block['content'] = t('block_description');
break;
}
return $block;
}
}
kind regards,
Daan
After taking a fresh look to my setup i saw what the problem was. I had a theme and a module with the same name. This caused some conflicts :/

Resources