I try to finish a plugin which imports data into my craftcms project. I already created a console based method/service, which I trigger/run in my shell. Inside my method(s) I receive data (XML or JSON) I parse my data and try to create and fill an entry of a specific channel I already created.
I tried "saveElement()" which doesn't work.
I found some tuts and informations for craftcms v2 (for example: https://docs.craftcms.com/api/v2/craft-entriesservice.html#public-methods)
Now i am stuck and i can not find any informations on how to solve this with craftcms v3.
Here is my last version of code after hours of different trys :(
$section = Craft::$app->sections->getSectionByHandle('testentry');
$entryTypes = $section->getEntryTypes();
$entryType = $entryTypes[0];
// Save Entry
//$entry = new EntryModel();
$entry = new \craft\elements\Entry();
$entry->sectionId = $section->id;
$entry->typeId = $entryType->id;
//$entry->locale = Craft::$app->i18n->getPrimarySiteLocaleId();
//$entry->authorId = 1; // TODO: Set author
$entry->enabled = true;
$entry->postDate = $post['post_date'];
$entry->slug = $post['post_name'];
// $entry->getContent()->title = $post['post_title'];
// $entry->setContentFromPost(array(
// 'body' => $postContent,
// 'categoryCareer' => NULL,
// ));
if (Craft::$app->elements->saveElement($entry)) {
$result = true;
}
else {
echo 'Could not save the Job entry.'."\n";
$result = false;
}
Related
I am using TinyButStrong for merge data in docx file. I have do same example data. For this i have write below code:
<?php
include_once('tbs_class.php');
include_once('../tbs_plugin_opentbs.php');
if(version_compare(PHP_VERSION,'5.1.0')>=0) {
if (ini_get('date.timezone')=='') {
date_default_timezone_set('UTC');
}
}
$TBS = new clsTinyButStrong; // new instance of TBS
$TBS->Plugin(TBS_INSTALL, OPENTBS_PLUGIN);
$entityname = $demodata['entity_name'];
$x_num = 3152.456;
$x_pc = 0.2567;
$x_dt = mktime(13,0,0,2,15,2010);
$x_bt = true;
$x_bf = false;
$x_delete = 1;
$template = 'draft_response_auto_populate.docx';
$TBS->LoadTemplate($template, OPENTBS_ALREADY_UTF8);
if (isset($_POST['debug']) && ($_POST['debug']=='current')) $TBS->Plugin(OPENTBS_DEBUG_XML_CURRENT, true); // Display the intented XML of the current sub-file, and exit.
if (isset($_POST['debug']) && ($_POST['debug']=='info')) $TBS->Plugin(OPENTBS_DEBUG_INFO, true); // Display information about the document, and exit.
if (isset($_POST['debug']) && ($_POST['debug']=='show')) $TBS->Plugin(OPENTBS_DEBUG_XML_SHOW); // Tells TBS to display information when the document is merged. No exit.
$TBS->MergeField('vs.duedate', $demodata['due_date']);
$TBS->PlugIn(OPENTBS_DELETE_COMMENTS);
$save_as = (isset($_POST['save_as']) && (trim($_POST['save_as'])!=='') && ($_SERVER['SERVER_NAME']=='localhost')) ? trim($_POST['save_as']) : '';
$output_file_name = str_replace('.', '_'.date('Y-m-d').$save_as.'.', $template);
if($save_as==='') {
$TBS->Show(OPENTBS_DOWNLOAD, $output_file_name); // Also merges all [onshow] automatic fields.
exit();
} else {
$TBS->Show(OPENTBS_FILE, $output_file_name); // Also merges all [onshow] automatic fields.
exit("File [$output_file_name] has been created.");
}
When i download word document its only reply handle $entityname = $demodata['entity_name'];
I want to replace all fields. I am attaching sample docx:
Date: [vs.duedate]
To,
Mr. ………………….,
The Assistant Commissioner, Audit-I
Delhi
Sub: Request for granting time extension for filing the reply to the notice received in form GST ADT-01bearing file no- [vs.eventnumber] dated 05.11.2020 ('Notice') received on dated [vs.eventdate]
Ref: [vs.eventdescription]
We [vs.entity_name] (hereinafter referred to as “we” or “the Company”), are registered as a regular taxpayer under the Goods and Services (“GST”) Act, bearing GSTIN [vs.registrationno]
For replace fields i have use:-
$TBS->MergeField('vs.duedate', $demodata['due_date']);
But it didn't replace. Please help me.
In order to merge all items in $demodata with fields [vs.*] you have to call
$TBS->MergeField('vs', $demodata);
But then item $demodata['due_date'] will be merged with the field [vs.due_date], not [vs.duedate].
I'm trying to pull a pretty basic report from DFP via API and the PHP library provided by Google, https://github.com/googleads/googleads-php-lib/. I've tried both creating the query in the UI and fetching that ReportQuery from the API and running it (per https://developers.google.com/doubleclick-publishers/docs/reporting#retrieving_a_saved_reportquery) as well as creating an ad hoc query. All create the request okay, which seems to imply that the query validates okay. Other API requests I've tested work fine, including fetching a list of line items etc.
The pertinent code is as follows:
$statementBuilder = (new StatementBuilder())
->where('AD_UNIT_NAME like \'prebid_\'');
# Create report query.
$reportQuery = new ReportQuery();
$reportQuery->setDimensions([
Dimension::AD_UNIT_NAME,
Dimension::CUSTOM_CRITERIA,
Dimension::DATE
]);
$reportQuery->setColumns([
Column::TOTAL_INVENTORY_LEVEL_IMPRESSIONS,
Column::TOTAL_INVENTORY_LEVEL_WITHOUT_CPD_AVERAGE_ECPM
]);
$reportQuery->setStatement($statementBuilder->toStatement());
$reportQuery->setAdUnitView(ReportQueryAdUnitView::TOP_LEVEL);
$reportQuery->setDateRangeType(DateRangeType::YESTERDAY);
# Create report job.
$reportJob = new ReportJob();
$reportJob->setReportQuery($reportQuery);
# Run report job.
$reportJob = $reportService->runReportJob($reportJob);
# Create report downloader.
$reportDownloader = new ReportDownloader($reportService, $reportJob->getId(), POLL_TIME_SECONDS);
# Wait for the report to be ready.
$reportDownloader->waitForReportToFinish();
# Change to your file location.
$filePath = sprintf('%s.csv.gz', tempnam(sys_get_temp_dir(),
'delivery-report-'));
printf("Downloading report to %s ...\n", $filePath);
# Download the report.
$reportDownloader->downloadReport('CSV_DUMP', $filePath);
Here's the error message I get from the API:
PHP Fatal error: Uncaught exception 'UnexpectedValueException' with message 'Cannot download report 1834923393 because it has a status of FAILED.' in ~/test/vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/Util/v201611/ReportDownloader.php:146
Stack trace:
#0 ~/test/vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/Util/v201611/ReportDownloader.php(116): Google\AdsApi\Dfp\Util\v201611\ReportDownloader->getDownloadUrl('CSV_DUMP')
#1 ~/test/dfp/get_prebid_unit_data.php(85): Google\AdsApi\Dfp\Util\v201611\ReportDownloader->downloadReport('CSV_DUMP', '/tmp/delivery-r...')
#2 {main}
thrown in ~/test/vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/Util/v201611/ReportDownloader.php on line 146
I have done similar kind of report using below code. Hope it would be helpful for you.
<?php
ini_set('display_errors', 'On');
error_reporting('E_ALL');
$date_to = isset($_GET['dateTo']) && !empty($_GET['dateTo']) ? date('Y-m-d', strtotime(trim($_GET['dateTo']))) : date('Y-m-d', strtotime('now'));
$date_from = isset($_GET['dateFrom']) && !empty($_GET['dateFrom']) ? date('Y-m-d', strtotime(trim($_GET['dateFrom']))) : date('Y-m-d', strtotime('-1 day'));
require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php';
//require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php';
require_once 'Google/Api/Ads/Dfp/Util/ReportUtils.php';
require_once 'Google/Api/Ads/Dfp/Util/DateTimeUtils.php';
try {
// Get DfpUser from credentials in "../auth.ini"
// relative to the DfpUser.php file's directory.
$user = new DfpUser();
// Log SOAP XML request and response.
// Get the ReportService.
$reportService = $user->GetService('ReportService', 'v201405');
// Create report job.
$reportJob = new ReportJob();
// Create report query.
$reportQuery = new ReportQuery();
// $reportQuery->dateRangeType = 'LAST_MONTH';
$reportQuery->dateRangeType = 'CUSTOM_DATE';
// $reportQuery->dateRangeType = 'YESTERDAY';
// $reportQuery->dateRangeType = 'TODAY';
$reportQuery->startDate = DateTimeUtils::GetDfpDateTime(new DateTime($date_from))->date;
$reportQuery->endDate = DateTimeUtils::GetDfpDateTime(new DateTime($date_to))->date;
//-- create PQL statement
// $reportStatement = new Statement();
// $reportStatement->query = "WHERE LINE_ITEM_TYPE = 'SPONSORSHIP'";
// $reportQuery->statement = $reportStatement;
//Date Salesperson Advertiser Order Line item Line item type Ad unit Salesperson ID Advertiser ID
//
//Order ID Line item ID Ad unit ID Total impressions Total impressions Total clicks Total CTR
$reportQuery->dimensions = array(
'DATE', 'SALESPERSON_NAME', 'ADVERTISER_NAME','ORDER_NAME', 'LINE_ITEM_NAME', 'LINE_ITEM_TYPE', 'AD_UNIT_NAME'
);
$reportQuery->columns = array(
'TOTAL_INVENTORY_LEVEL_IMPRESSIONS', 'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS', 'TOTAL_LINE_ITEM_LEVEL_CLICKS', 'TOTAL_LINE_ITEM_LEVEL_CTR', 'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE', 'TOTAL_LINE_ITEM_LEVEL_WITH_CPD_AVERAGE_ECPM'
);
$reportJob->reportQuery = $reportQuery;
// Run report job.
$reportJob = $reportService->runReportJob($reportJob);
do {
printf("<p>Report with ID '%s' is running.", $reportJob->id);
sleep(5);
// Get report job.
$reportJob = $reportService->getReportJob($reportJob->id);
} while ($reportJob->reportJobStatus == 'IN_PROGRESS');
if ($reportJob->reportJobStatus == 'FAILED') {
printf("Report job with ID '%s' failed to finish successfully.</p>", $reportJob->id);
} else {
printf("Report job with ID '%s' completed successfully.</p>", $reportJob->id);
$reportJobId = $reportJob->id;
//-- Set the format of the report (e.g., CSV_DUMP) and download without compression so we can print it.
$reportDownloadOptions = new ReportDownloadOptions();
// $reportDownloadOptions->exportFormat = 'CSV_DUMP';
$reportDownloadOptions->exportFormat = 'TSV';
$reportDownloadOptions->useGzipCompression = false;
//-- get download url of the report
$downloadUrl = $reportService->getReportDownloadUrlWithOptions($reportJobId, $reportDownloadOptions);
//-- get printed data of the report from the download url
$report = ReportUtils::DownloadReport($downloadUrl);
//-- now parse the report data and manage it to view/store it in Database
// print $report.'<br><br>';die;
}
} catch (OAuth2Exception $e) {
ExampleUtils::CheckForOAuth2Errors($e);
// echo "check";
} catch (ValidationException $e) {
ExampleUtils::CheckForOAuth2Errors($e);
} catch (Exception $e) {
print $e->getMessage() . "\n";
}
Sometimes sleeping on it makes all the difference. Notably, the same query, when fetched via ReportService::getSavedQueriesByStatement, returns the following:
Google\AdsApi\Dfp\v201611\SavedQuery {#52
#id: 468197553
#name: "Prebid KV Query"
#reportQuery: Google\AdsApi\Dfp\v201611\ReportQuery {#49
#dimensions: array:3 [
0 => "AD_UNIT_NAME"
1 => "CUSTOM_CRITERIA"
2 => "DATE"
]
#adUnitView: "TOP_LEVEL"
#columns: array:2 [
0 => "TOTAL_INVENTORY_LEVEL_IMPRESSIONS"
1 => "TOTAL_INVENTORY_LEVEL_WITHOUT_CPD_AVERAGE_ECPM"
]
#dimensionAttributes: null
#customFieldIds: null
#contentMetadataKeyHierarchyCustomTargetingKeyIds: null
#startDate: null
#endDate: null
#dateRangeType: "YESTERDAY"
#statement: Google\AdsApi\Dfp\v201611\Statement {#48
#query: " where ad_unit_name like 'prebid_'"
#values: null
}
#useSalesLocalTimeZone: false
#includeZeroSalesRows: false
}
#isCompatibleWithApiVersion: true
}
Note the lack of % in the query.
However, when generating the report, % are required in the LIKE statement in order to properly filter.
The interesting thing here is that even pulling the saved query and generating a ReportJob from that without modification fails, which seems to imply that you cannot programmatically run a saved query that contains a LIKE filter?
I have a script to create new thread with via scritp in vbulletin
// Create a new datamanager for posting
$threaddm =& datamanager_init('Thread_FirstPost', $vbulletin, ERRTYPE_ARRAY, 'threadpost');
// Set some variable and information
$forumid = 87; // The id of the forum we are posting to
$userid = 2;
$_POST["title"] = $vinanghinguyen_title;
$_POST["content"] = $final_content; // The user id of the person posting
$title = $_POST["title"]; // The title of the thread
$pagetext = $_POST["content"]; // The content of the thread
$allowsmilie = '1'; // Are we allowing smilies in our post
$visible = '1'; // If the post visible (ie, moderated or not)
// Parse, retrieve and process the information we need to post
$foruminfo = fetch_foruminfo($forumid);
$threadinfo = array();
$user = htmlspecialchars_uni( fetch_userinfo($userid) );
$threaddm->set_info('forum', $foruminfo);
$threaddm->set_info('thread', $threadinfo);
$threaddm->setr('forumid', $forumid);
$threaddm->setr('userid', $userid);
$threaddm->setr('pagetext', $pagetext);
$threaddm->setr('title', $title);
$threaddm->set('allowsmilie', $allowsmilie);
$threaddm->set('visible', $visible);
// Lets see what happens if we save the page
$threaddm->pre_save();
if(count($threaddm->errors) < 1) {
// Basically if the page will save without errors then let do it for real this time
$threadid = $threaddm->save();
unset($threaddm);
} else {
// There was errors in the practice run, so lets display them
var_dump ($threaddm->errors);
}
/*======================================================================*\
It can create new thread with title, forumid, userid.....but it not insert tag. I want insert with this script. thank for help
I am trying to retrieve the data from a mysql data and show it in a PHP page running a session. The code runs in a separate page. And the data is retrieved as Image in another page.
The main problem is no matter what kind of coding that I put above the default graph coding, it will become a broken image. FYI I have already enabled php_gd2.dll and the extension in my php.ini file is set to the extension folder. Are there any other fixes that has to be made in any of the files?
<?php
session_start();
if($_SESSION['username'])
{
require "dbc.php";
echo "<h2>Patient Glucose Data</h2>";
$username = $_SESSION['username'];
$query_view = mysql_query("SELECT * FROM user_glucose WHERE username='$username'");
$numrows = mysql_num_rows($query_view);
if ($numrows != 0)
{
while ($rows = mysql_fetch_assoc($query_view))
{
$print_day1 = $rows['Day1'];
$print_day2 = $rows['Day2'];
$print_day3 = $rows['Day3'];
$print_day4 = $rows['Day4'];
$print_day5 = $rows['Day5'];
$print_day6 = $rows['Day6'];
$print_day7 = $rows['Day7'];
$print_day8 = $rows['Day8'];
$print_day9 = $rows['Day9'];
$print_day10 = $rows['Day10'];
$print_day11 = $rows['Day11'];
$print_day12 = $rows['Day12'];
$print_day13 = $rows['Day13'];
$print_day14 = $rows['Day14'];
}
}
require('/jpgraph-3.5.0b1/src/jpgraph.php');
require('/jpgraph-3.5.0b1/src/jpgraph_line.php');
// data
$ydata =
array($print_day1,$print_day2,$print_day3,$print_day4,$print_day5,$print_day6,$print_day7,$print_day8,$print_day9);
// Create the graph. These two calls are always required
$graph = new Graph(500,500);
$graph->SetScale('textlin');
$graph->xaxis->title->Set("Number of Days");
$graph->yaxis->title->Set("Glucose Concentration");
// Create the linear plot
$lineplot=new LinePlot($ydata);
$lineplot->SetColor('blue');
// Add the plot to the graph
$graph->Add($lineplot);
// Display the graph
$graph->Stroke();
}
?>
I have downloaded 2012_2 PHP Toolkit for Netsuite. With less or no documentation it would be great if someone can give me headstart on how to connect to a Custom Record List Created in Netsuite
The list is labs under lists->support in netsuite.
Through PHP i want to enter data to that list I dont need the entire code, I just need a headstart on how to connect to that custom record I created in netsuite. I have the internal id of the custom record and the name of the custom record in netsuite.
For others to refer later on this could be helpful
$service = new NetSuiteService();
// Create a object for lab name in netsuite
$labName = new SelectCustomFieldRef();
$labName->value = new ListOrRecordRef();
$labName->value->internalId = $lab_number; // your input
$labName->internalId = "xxxxxx"; // internal id of the input in Netsuite
$labCustomRecord = new CustomRecord();
$labCustomRecord->recType = new RecordRef();
$labCustomRecord->customForm = "xxxx"; // form id
$labCustomRecord->recType->internalId = "xx"; // internal id
$labCustomRecord->customFieldList = new CustomFieldList();
$labCustomRecord->customFieldList->customField = $labName
$addRequest = new AddRequest();
$addRequest->record = $labCustomRecord;
if(!$addResponse[$i]->writeResponse->status->isSuccess) {
echo "<pre>"; print_r("Error"); echo "</pre>"; exit();
} else {
echo "<pre>"; print_r("Success"); echo "</pre>"; exit();
}
Below is a sample code on how to add new record for a custom record type using PHP Toolkit 2012.2
//create an instance of the fields of the custom record
$customFieldList = new StringCustomFieldRef();
$customFieldList->internalId = "custrecord_name";
$customFieldList->value = "Test from PHP toolkit";
$basicCustomRecord = new CustomRecord();
$basicCustomRecord->name = "PHP Toolkit 2012.2";
$basicCustomRecord->recType = new RecordRef();
$basicCustomRecord->recType->internalId = "14"; //Record Type's internal ID (Setup > Customization > Record Types > Basic Record Type (Internal ID=14)
$basicCustomRecord->customFieldList = new CustomFieldList();
$basicCustomRecord->customFieldList->customField = $customFieldList;
$addRequest = new AddRequest();
$addRequest->record = $basicCustomRecord;
$addResponse = $service->add($addRequest);
if (!$addResponse->writeResponse->status->isSuccess) { echo "ADD ERROR"; exit();}
else { echo "ADD SUCCESS, id " . $addResponse->writeResponse->baseRef->internalId;}
?>
this same code is available in SuiteAnswers. There are a number of other sample codes for PHP Toolkit 2012.2 in SuiteAnswers as well. If you have time, you can review those code for your future reference.
Regards!