Storing external API into Drupal 8 database - drupal

I am using PHP and able to fetch information from an API. I am new to Drupal and I would like to know how the data fetched from an external API can be stored inside a Drupal database. I have created the nodes through the Drupal interface and this has created the corresponding tables in the database.
What would be the best approach for this implementation?
Thank you

The easiest solution would probably be to use Feeds.
Feeds is the alpha/dev stages for Drupal 8 but it should be useable as more than 3000 installs have been reported (at the time of writing).
Feeds allows you to map an external api to specific fields in your content type and save them as local nodes. It can also be configured to fetch data at intervals or one off.
For a more custom solution you should create a custom module that fetches the API data and save them as fields in a content type sort of like this
use \Drupal\node\Entity\Node;
$node = Node::create([
'type' => 'article',
'title' => 'Article test',
///...
]);
$node->save();

Related

how to add node in through Drupal API

In order to insert an article to Drupal there are thee ways of doing that:
by admin panel - really slow and not feasable if talking about 400 articles
by pure sql - number of tables that have to maintained and calculated (content, core, cat etc.) is quite high and it's not really reliable
by using drupal API - that's something that I was trying to implement but can't find a good documentation on it. What I'm trying to achieve is to use drupal classes and insert content (ie. running a PHP file with (catid,title,introtext....))
Example: what i want to add node in xyz.com/drupal site but my php code should be run in irankmedi.com
Can you please point me into direction where I can find some info on how to manage articles and categories this way?
Thanks in advance
If your request is very specific and you can't find a module that does what you need it shouldn't be too difficult to make a module on your own and import (create drupal) content from your code. Should be something like this:
Create a php file that will do the job.
At start of your script include standard Drupal's bootstrap code so you'll have all Drupal's functionality available in your script
Make code that will read content (from database or feed or something else).
Use Drupal api to insert node programatically:
https://www.drupal.org/node/1388922
Call your script manually or set cron to call it on specific time periods.
First you have to read RSS feed in drupal custom module. Then, following code can create node programatically.
$node = new stdClass();
$node->type = 'blog'; // This type should exist
node_object_prepare($node); // Sets some defaults.
$node->language = LANGUAGE_NONE; // The language of the default
$node->title = "testnode";
$node->body[LANGUAGE_NONE][0]['value'] = "Body";
node_save($node); // function that actually saves node in database

Integrate Smarty Site with Drupal site

I am currently working on a site which is on smarty based.The name of the site is http://example.com
I built a new folder in the root path and installed droupon (which is a component of drupal for buying or creating any deal) on the folder.The site url is http://example.com/coupon
Now I want to integrate or merge this two sites.So that when a registered user access example.com then he can access the example.com/coupon with his session user id.
But this is the problem.
Is this really possible to pass data from smarty based site (example.com) to drupal site example.com/coupon ?
Please help me.
I would write at module in Drupal that looks at $_SESSION and creates and/or login the user at the Drupal-site. Perhaps the rules module can do that work, but you will probably need to implement a rules-hook to grab the relevant session data as input to the rules component.
Here are a few lines of code that do some of the work but you need to implement hook_menu aswell to register an entrypoint for the integration.
//register user
$passwd = user_password();
$edit = array(
'name' => $_SESSION['username'],
'pass' => $passwd,
'mail' => $_SESSION['email'],
'init' => $_SESSION['email'],
'status' => 1,
'access' => REQUEST_TIME,
);
$uu = drupal_anonymous_user();
$u = user_save($uu, $edit);
//Login
global $user;
$user = user_load($u->uid);
$login_array = array ('name' => $username);
user_login_finalize($login_array);
However, Im not sure this is the best way to go about it. Sharing data in the same session-namespace between 2 different applications will probably lead to errors on both sides. Is it not better to implement the whole site in Drupal from the beginning?

How to run some SQL commands on Drupal 7 User Rregistration

I need to run a SQL command right after a new user account has been created (I need to obtain new User ID also). (in Drupal 7)
How can I do this?
In a custom drupal module, use hook_user_insert.
within that function the $account variable with have the new user data and user id number.
To run custom sql query, you can use drupal's db_query function.
If you need to learn about custom drupal module development, take a look at the example modules.
Build a custom module with hook_user_insert implementation.
Here's a code sample that saves the new user's id into a table called test_table.
function [YOUR_MODULE]_user_insert(&$edit, $account, $category) {
$newUserId = $account->uid;
db_insert('test_table')
->fields(array(
'user_id' => $newUserId,
))
->execute();
}

How do I add taxonomy terms using Drupal Migrate

I'm using the migrate module to copy data from several sources to a new drupal installation. So far, I'm able to replicate a lot of what I need from the examples provided with the module. I'm currently stuck on adding terms or taxonomy to newly created nodes. The example shows:
// These are related terms, which by default will be looked up by name
$this->addFieldMapping('migrate_example_beer_styles', 'terms')
->separator(',');
I've tracked down the migrate_example_beer_styles destination mapping and it seems to be the machine name for that taxonomy.
I've tried imitating this behavior with every variation of what my machine_name should be, but the terms never seem to get associated:
By id:
// where source breed_id is '1,100' - it finds mapped values accordingly
$this->addFieldMapping('breeds', 'breed_id')
->sourceMigration('BreedMigration')
->separator(',')
And, by name:
// where source breeds is 'Dogs,German Shepherd'
$this->addFieldMapping('breeds', 'breeds')
->separator(',');
Am I wrong assuming the destination mapping is the machine name for a taxonomy?
This version of the migrate module was released recently, I haven't found any other helpful examples on the web.
This question still seems to be getting some views, so I thought I'd add what else I've discovered. While the accepted answer works, you are able to map Vocabs on ID:
$this->addFieldMapping('Exact Case Sensitive Vocab Name', 'source_field_name')
->sourceMigration('ExactSourceClassName')
->arguments(array('source_type' => 'tid'))
->separator(',');
->separator(',') used for passing a delimited string of source ids. Obviously, leave that off if you're mapping an array of values.
I'm currently working with migrate module myself, and I agree that the documentation is somewhat wanting at this point. :)
The 'machine name' of a vocabulary is listed in the Vocabulary table, in the field 'module'. Try using that value. Do note that you need to feed the text into the mapping, not the ids.
This is my first post on stackoverflow, so I apologize in advance if this isn't the accepted way to submit more information concerning this issue...
I've been stumbling around with the Migrate module for the past few days and was looking for a way to do this in Drupal 7. I had a comma-delimited list of taxonomy ids within an XML field that I wanted to use, but every example I found was retrieving from an external class, or from a database source.
Anyway, through trial and error, I found that you can use a field within the migrate class, rather than reference an external term migration class.
$this->addFieldMapping('field_article_type', 'category_id')
->arguments(array('source_type' => 'tid'))
->xpath('/article/category_id')
->separator(',');
Check out the taxonomy csv import module at http://drupal.org/project/taxonomy_csv.
It was easy to use and did what it was supposed to and more.
I ended up only using the migrate module for importin gNodes and used this module for the taxonomy. It was a pleasure to use.

Drupal sharing content between two websites

I am farmiar with building drupal sites but not sure what the best way to implement this scenario. I have two domain names mydomain.com and mydomain2.com. I need to have a conten type with some fields in. i.e.
ContentType
Field - Title
Field - Body
Field - Picture
Field - Price
I want both sites to use the same data for the custom conten type. So you enter the data on one site and it will be updated on both.
mydomain.com will show the follwoing infromation from the content type.
ContentType
Field - Title
Field - Body
Field - Picture
mydomain2.com will show all the data.
mydomain.com and mydomain2.com will have diffent look nd feel. And each domain may use some diffent modules. mydomain2.com will be using ubercart and mydomain.com will not.
Would I use mutlisite here and somehow sharte the tables. Use one instance of drupal and do the rest with theming? Use features and context?
Any help would be apreciated.
After doing some research this may be what I need http://drupal.org/project/domain. A case study can be found at http://drupal.org/node/369398.
Still wondering if there are otherways so not acepting this as the answer yet.
You just need to share tables between the sites.
You can share specific tables (best done in logicaly groups) accross Drupal 7 installs by adding something like this to your settings.php file:
$my_db_users = 'drupal_users.shared_';
$my_db_content = 'drupal_content.shared_';
$databases['default']['default'] = array(
'driver' => 'mysql',
'database' => 'defaultdatabase',
'username' => 'databaseuser',
'password' => 'databasepassword',
'host' => '127.0.0.1',
'port' => 3066,
'prefix' => array(
'default' => 'default_',
'users' => $my_db_users,
'sessions' => $my_db_users,
'role' => $my_db_users,
'authmap' => $my_db_users,
'node' => $my_db_content,
'node_revisions' => $my_db_content,
'node_type' => $my_db_content,
),
'collation' => 'utf8_general_ci',
);
In the above instance, we set variables that point to different databases for certain groups of tables. So in the above example, we need three databases: defaultdatabase, drupal_users, and drupal_content.
Then in the array, we set the default table prefix 'default' => 'default_', and that says: "store all tables, unless otherwise specified, in defaultdatabase and make their table prefix default_." We're also saying: "store all users, sessions, roles, and user-role mappings (authmap) in the database drupal_users with the table prefix shared_." And lastly, we're saying: "store all node types, nodes, and their revisions in the database drupal_content with the table prefix shared_."
With great power comes great responsibility:
You will completely hose your install if you don't keep logical groups of tables together.
What are logical groups of tables? Well, probably any table with the prefix node_ in your current install should probably be moved to the shared database. Most well structured modules (say node_access) will have their table name's prefixed with something logical. Based on your modules, ensure you keep groups of tables in the right place (in the default database for site-specific data, or in another database for shared data.)
Add a little bling:
I did a similar install where the users and roles were shared, but NOT the authmap. To what end?
Well, if you do this, you could have the same users and groups accross a large network of sites while still allowing users different permissions on different sites. On one site you may be an editor, but on another you'd be an author.
The Domain module looks good (although I haven't used it). It may be overkill for your needs.
If you want something very simple you can create a module which sets the global $custom_theme in hook_init() depending on the domain.
For me, if this was a critical portion of the site, I would create a custom module. There are a few guides out there to create node_types through modules. I happen to like this one.
That way, you have a basic structure of your data in a custom table and then can customize the call for displaying the data to either include the price column or not.
Again, some may see this as too much work but if you aren't familiar with Drupal module development, this is a great way to learn. If you are familiar, it should be quick and simple.

Resources