Some years ago I made a Drupal 7 site. I want to remake the site with Drupal 9.
In Drupal 7 I added nodes programmatically with this PHP code:
<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$data = $_GET['d'];
AddNewNode($data);
function AddNewNode($data)
{
list($installlanguage, $playerid) = explode('|', $data);
$node = new stdClass();
$node->type = 'new_install';
node_object_prepare($node);
$node->language = LANGUAGE_NONE;
$node->field_hm_new_installlanguage[$node->language][0]['value'] = $installlanguage;
$node->field_hm_new_install_playerid[$node->language][0]['value'] = $playerid;
node_save($node);
}
?>
This code isn't working with Drupal 9.
I tried to search Google for "drupal 9 add content programmatically", but I don't seem to get any useful results. Most links are about Drupal 8.
Can someone point me in the right direction?
Thank you!
You can still do this if you really want. However, there are much better ways of managing content creation now (look at the examples for "migrate" module with e.g. JSON or CSV files).
The equivalent of what you have previously would be something like this;
<?php
use Drupal\Core\Database\Database;
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
$autoloader = require_once 'autoload.php';
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
defined('DRUPAL_ROOT') or define('DRUPAL_ROOT', getcwd());
$node = \Drupal::entityTypeManager()->getStorage('node')->create([
'type' => 'article',
'title' => 'something something',
'langcode' => 'en',
'field_something' => ... // Check the structure as it differs between fields.
]);
// You don't have to do it all in one array.
$node->set('field_something_2', 'something');
$node->save();
Take a look here for more information https://drupalbook.org/drupal/9111-working-entity-fields-programmatically.
According to this blog post,
the code is simpler (compared to #Pobtastic's answer) when you use it within a Drupal PHP page:
use Drupal\node\Entity\Node;
$node = Node::create([
'type' => 'article',
'langcode' => 'en',
'title' => 'My test!',
'body' => [
'summary' => '',
'value' => '<p>The body of my node.</p>',
'format' => 'full_html',
],
]);
$node->save();
\\ Add URL alias :
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), "/my/path", "en");
Source:
Related
I am using "nesk/puphpeteer": "^2.0" and I want to select the following dropdown of a datatable:
Find below my minimum example:
<?php
require_once '../vendor/autoload.php';
use Nesk\Puphpeteer\Puppeteer;
use Nesk\Rialto\Data\JsFunction;
$debug = true;
$puppeteer = new Puppeteer([
'read_timeout' => 100,
'debug' => $debug,
]);
$browser = $puppeteer->launch([
'headless' => !$debug,
'ignoreHTTPSErrors' => true,
]);
$page = $browser->newPage();
$page->goto('https://www.psacard.com/auctionprices#0%7Cpokemon');
// select dropdown
// drop-down activate
$selectElemDropDown = $page->querySelectorXPath('//*[#id="DataTables_Table_0_length"]/label/select');
$selectElemDropDown[0]->click();
$selectElemOptTwo = $page->querySelectorXPath('//*[#id="DataTables_Table_0_length"]/label/select/option[2]');
$selectElemOptTwo[0]->click();
$browser->close();
I tried clicking on the dropdown and then clicking again to select the element, which does not work.
I puppeteer JS there is a function called page.select(selector, ...values).
How can I do this function in puphpteer in my minimum viable example?
I appreciate your replies!
You must require autoload correctly if you use it this way and it doesn't work you are doing something wrong. Also enter terminal from project folder and use composer dump-autoload after you add the require 'vendor/autoload.php' line to project.
require 'vendor/autoload.php';
use Nesk\Puphpeteer\Puppeteer;
use Nesk\Rialto\Data\JsFunction;
$debug = true;
$puppeteer = new Puppeteer([
'read_timeout' => 100,
'debug' => $debug,
]);
$browser = $puppeteer->launch([
'headless' => !$debug,
'ignoreHTTPSErrors' => true,
]);
$page = $browser->newPage();
$page->goto('https://www.psacard.com/auctionprices#0%7Cpokemon');
$page->waitForTimeout(8000);
// set select value to 100
$page->select('select[name=DataTables_Table_0_length]', '100');
$browser->close();
page.select is also available in php, it accept a css selector instead of xpath.
<?php
require_once './vendor/autoload.php';
use Nesk\Puphpeteer\Puppeteer;
use Nesk\Rialto\Data\JsFunction;
$debug = true;
$puppeteer = new Puppeteer([
'read_timeout' => 100,
'debug' => $debug,
]);
$browser = $puppeteer->launch([
'headless' => !$debug,
'ignoreHTTPSErrors' => true,
]);
$page = $browser->newPage();
$page->goto('https://www.psacard.com/auctionprices#0%7Cpokemon');
// wait for select element to appear
$page->waitForSelector('select[name=DataTables_Table_0_length]');
// set select value to 100
$page->select('select[name=DataTables_Table_0_length]', '100');
$browser->close();
We are using this GitHub PHP library for adding javascript in to the head of shopify pages using script tag but we have got stuck somewhere,
it redirects well. We go to app screen to get permission also when we click on install it redirects to redirect page and gives error. in my error log.
Uncaught PHPShopify\Exception\ApiException: script_tag -
expected Array to be a Hash in
This is our app code
<?php
require '/home/xxx/public_html/shopify/1/vendor/autoload.php';
$config = array(
'ShopUrl' => 'xyyy.myshopify.com',
'ApiKey' => 'a07235d5cxx4af2239ea02fe197',
'SharedSecret' => '7ae8a450xxxx2576cf5e7a606c3',
);
PHPShopify\ShopifySDK::config($config);
$shopify = new PHPShopify\ShopifySDK;
$scopes = array('read_orders','read_script_tags','read_products', 'write_script_tags');
$redirectUrl = 'https://xxxx.com/shopify/1/99.php/auth/callback';
$auth = \PHPShopify\AuthHelper::createAuthRequest($scopes, $redirectUrl);
$src = "https://xxxx.com/modules/script72paid.js";
$finalurl='https://xxxxx.myshopify.com/admin/script_tags.json'.
$shopify->ScriptTag->post(array("post"), ''.$finalurl.'', array( "script_tag" => array( "event"=>"onload", "src"=>$src)));
?>
and this is our redirect link code
<?php
require '/home/xxxxxx/public_html/shopify/1/vendor/autoload.php';
$config = array(
'ShopUrl' => 'xxxx.myshopify.com',
'ApiKey' => 'a07235d5cxxxxxx9ea02fe197',
'SharedSecret' => '7ae8a45xxxxxxx76cf5e7a606c3',
);
PHPShopify\ShopifySDK::config($config);
$shopify = new PHPShopify\ShopifySDK;
$accessToken = \PHPShopify\AuthHelper::getAccessToken();
$config2 = array(
'ShopUrl' => 'xxxx.myshopify.com',
'AccessToken' => $accessToken,
);
$shopify2 = new PHPShopify\ShopifySDK($config2);
$src = "https://xxxxx.com/modules/script72paid.js";
$finalurl='https://xxxxx.myshopify.com/admin/script_tags.json'.
$shopify2->ScriptTag->post(array("post"), ''.$finalurl.'', array( "script_tag" => array( "event"=>"onload", "src"=>$src)));
?>
How do we avoid this error with expected Array to be a Hash?
Any help will be great.
Check that you are passing the correct parameters to $shopify->ScriptTag->post() by looking at the function in your copy of the library. Different versions of the library and documentation may have changed something.
Check that those parameters are in the correct order.
Check that all of the arrays you are passing are not actually meant to be objects.
Check if any of the arrays need to wrapped in another array.
I'm trying to translate my long and lat from my html 5 location request into a readable adress. I'm trying to use openCage Geocoding for this but it keeps giving the nex error:
Class 'Geocoder\Provider\OpenCage\OpenCage' not found
this is my code, like the documentation said
<?php
require "vendor/autoload.php";
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;
use Geocoder\Query\GeocodeQuery;
use Geocoder\Query\ReverseQuery;
$adapter = new GuzzleAdapter();
$provider = new \Geocoder\Provider\OpenCage\OpenCage($adapter, 'APIKEY');
$geocoder = new \Geocoder\StatefulGeocoder($provider, 'en');
$results = $geocoder->geocodeQuery(GeocodeQuery::create('1 Hacker Way, Menlo Park, 94025'));
# print_r($results);
$coords = $results->first()->getCoordinates();
echo json_encode([ 'lat' => $coords->getLatitude(), 'lon' => $coords->getLongitude() ]) . "\n";
?>
From the documentation you linked to:
There are two PHP libraries you can use
You have installed one and used the sample code from the other. So, either run this command:
composer require willdurand/geocoder
And keep using the code above.
Or, replace your code with something like this:
$geocoder = new \OpenCage\Geocoder\Geocoder('YOUR-API-KEY');
$result = $geocoder->geocode('1 Hacker Way, Menlo Park, 94025');
if ($result && $result['total_results'] > 0) {
$first = $result['results'][0];
echo json_encode([
'lat' => $first['geometry']['lat'],
'lon' => $first['geometry']['lng'],
]);
}
I am using the upper mentioned library (Google Cloud Vision Client Library v1) in PHP to assign labels to images... so far so good. It all works, except it returns fewer results than on the google test page... as far as I understand it has to do with a "max_results" parameter which defaults to 10, but I am not able to find where/how to set it manually...
There was a similar question here on Python and there it was as simple as passing it as a parameter - I have tried many options to do this in PHP, but apparently I am doing something wrong...
Here is a link to the documentation : https://googleapis.github.io/google-cloud-php/#/docs/cloud-vision/v0.19.3/vision/v1/imageannotatorclient?method=labelDetection
I am guessing I have to pass it to the "optionalArgs" parameter... but not exactly sure how to do this...
Here is more or less what my code is:
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
$this->client = new ImageAnnotatorClient();
$response = $this->client->labelDetection(...THE IMAGE...);
$labels = $response->getLabelAnnotations();
if ($labels) {
foreach ($labels as $label) {
// do something with $label->getDescription()
}
}
Anyone got an idea how to get more results in the $labels array?
New Method
Since the other answer I provided seems to be deprecated, I am going to provide a sample that uses the setMaxResults method on the Feature object.
$imageAnnotatorClient = new ImageAnnotatorClient();
$gcsImageUri = 'some/image.jpg';
$source = new ImageSource();
$source->setGcsImageUri($gcsImageUri);
$image = new Image();
$image->setSource($source);
$type = Feature_Type::FACE_DETECTION;
$featuresElement = new Feature();
$featuresElement->setType($type);
$featuresElement->setMaxResults(100); // SET MAX RESULTS HERE
$features = [$featuresElement];
$requestsElement = new AnnotateImageRequest();
$requestsElement->setImage($image);
$requestsElement->setFeatures($features);
$requests = [$requestsElement];
$imageAnnotatorClient->batchAnnotateImages($requests);
Deprecated Method
The maxResults value gets specified in the Image constructor
An example of this code can be found in the source code for the Image object.
$imageResource = fopen(__DIR__ . '/assets/family-photo.jpg', 'r');
$image = new Image($imageResource, [
'FACE_DETECTION',
'LOGO_DETECTION'
], [
'maxResults' => [
'FACE_DETECTION' => 1
],
'imageContext' => [
....
]
]
]);
OK, so for anybody who still may need this here is a working example
use Google\Cloud\Vision\Image;
use Google\Cloud\Vision\VisionClient;
$imageResource = fopen(__DIR__ .'/'. $fileIMG, 'r');
$thePic = new Image($imageResource, [
'LABEL_DETECTION',
'LOGO_DETECTION',
'TEXT_DETECTION'
], [
'maxResults' => [
'LABEL_DETECTION' => 20,
'LOGO_DETECTION' => 20,
'TEXT_DETECTION' => 20
],
'imageContext' => []
]);
$vision = new VisionClient();
$result = $vision->annotate($thePic);
$finalLabels = array();
// do the same for $results->text(), $results->logos()
if($result->labels()){
foreach ($result->labels() as $key => $annonObj) {
$tmp = $annonObj->info();
$finalLabels[] = $tmp['description'];
}
}
But... as it says in the official documentation
Please note this client will be deprecated in our next release. In order
to receive the latest features and updates, please take
the time to familiarize yourself with {#see Google\Cloud\Vision\V1\ImageAnnotatorClient}.
So I still need a way to do this using the ImageAnnotatorClient class... any ideas anyone?
Apparently this is a common problem but I have not been able to figure out how to get a Zend Captcha Image to show up, it will create the image and it will create the hidden element but the image tag never shows up, does anyone have a solution??
Here is the code that doesn't work:
<?php
class Application_Form_Contact extends Zend_Form
{
public function init()
{
/* Form Elements & Other Definitions Here ... */
$this->setAction('/contact/')->setMethod('post');
$element = new Zend_Form_Element_Text('name');
$element->setLabel('Name:')
->setRequired(true)
->addFilter('HtmlEntities');
$this->addElement($element);
$element = new Zend_Form_Element_Text('phone');
$element->setLabel('Phone:')
->setRequired(true)
->addFilter('HtmlEntities');
$this->addElement($element);
$element = new Zend_Form_Element_Text('email');
$element->setLabel('Email:')
->setRequired(true)
->addValidator('EmailAddress', true)
->addFilter('StripTags')
->addFilter('HtmlEntities')
->addFilter('StringToLower')
->addFilter('StringTrim');
$this->addElement($element);
$comments = $this->createElement('textarea', 'comments')
->setLabel('Comments:')
->setRequired(true)
->setOptions(array('style'=>'width:95%;'))
->addFilter('StripTags')
->addFilter('HtmlEntities')
->addFilter('StringTrim');
$this->addElement($comments);
$captcha= new Zend_Form_Element_Captcha('captcha', array(
'id'=>'captchas',
'title'=>'Security Check.',
'captcha' => array(
'captcha' => 'Image',
'required' => true,
'font'=> PUBLIC_PATH . '/verdana.ttf',
'wordlen'=>'4',
'width'=>'80',
'height'=>'50',
'ImgAlign'=>'left',
'imgdir'=> PUBLIC_PATH . '/images/captcha/',
'DotNoiseLevel'=>'0',
'LineNoiseLevel'=>'0',
'Expiration'=>'1000',
'fontsize'=>'16'
)));
$this->addElement($captcha);
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Send');
$this->addElement($submit);
}
}
I've only got two ideas that might help:
Check to make sure your GD extension is enabled in php.
It requires the GD extension compiled with TrueType or Freetype support. Currently, the Zend_Captcha_Image adapter can only generate PNG images.
you may want to specify the imgUrl =>
setImgUrl($imgUrl) and getImgUrl() allow you to specify the relative path to a CAPTCHA image to use for HTML markup. The default is "/images/captcha/".
also just for information you don't need to set the element as required as the captcha is always required.
As noted, the captcha adapter itself acts as a validator for the element. Additionally, the NotEmpty validator is not used, and the element is marked as required. In most cases, you should need to do nothing else to have a captcha present in your form.
Try to edit your captcha down to bare bones
$captcha = new Zend_Form_Element_Captcha('Captcha', array(
'captcha' => array(
'captcha' => 'Image',
'wordLen' => 6,
'timeout' => 300,
'width' => 300,
'height' => 100,
'imgUrl' => '/captcha',
'imgDir' => APPLICATION_PATH . '/../public/captcha',
'font' => APPLICATION_PATH . '/../public/fonts/LiberationSansRegular.ttf')));
just get anything to work then add back what you need 'till you find the problem. I suspect you have a problem with one of your paths.
Start with the APPLICATION_PATH constant then change to PUBLIC_PATH if you feel it's better.
check your file permissions; I had to give group write access before the image would write.