Jump to content
kreativmonkey

Import Posts with API

Recommended Posts

Hi,

i want to import stuff from Drupal to Processwire and have create an importscript but some things doesn't work.

I import a list of questions from users and i will manipulate the page created date (thats work fine) and change the User to the right one. If the User dosn't exist, i will creat a new one. But this is the first problem i have, no user will be change or create...

The second problem is to find out if the page does alrady exist or not. If the Page exist i will only modify some fields, otherwise i will create a new page.....

To find out if the Page exist and whats the Page ID do i also need to import the Comments.....

readCSV.php:

// Read the CSV file and get an array of rows
function readCSV($file){
	$lines = array();
	
	foreach(file($file, FILE_IGNORE_NEW_LINES) as $line){
		$lines[] = str_getcsv($line);
	}	

	return $lines;
}

import.php:

while($i < $countArray){
  // Initzalisierung der Variablen
	$title = $data[$i][0];
	$date = $data[$i][6];
	#$summary = '';
	$body = $data[$i][1];
	$categorys = $data[$i][4];
	$tags = $data[$i][3];
	#$images = '';
	$authorName = $data[$i][5];

	$sanitizTitle = $sanitizer->pageName($title);
	$post = $pages->get("template=$template, name=$sanitizTitle");
	if(empty($post)){
	  $p = new Page(); // create new page object
	  $p->template= $template; //set template post
	  $p->parent = wire('pages')->get('/$parent/'); //set the parent
	  $p->name = $sanitizTitle; // SANITIZE!!!!
	  $p->title = $title;
	  // added by Ryan: save page in preparation for adding files (#1)
	  $p->save();

	  $p->created = $date; // Timestamp!!!
		$p->save(array('quiet' => true)); // To save the created Date

		$p->body = $body;
	  // $p->summary = $summary;
	  // Looking for the inizialisation
	  $p->tags = $tags;
	  $p->categories = $categorys;

		$p->save();
		echo 'Created Page: '. $title .'<br>';
		$authorNameSanitiz = $sanitizer->name($authorName);

	  if($users->get($authorNameSanitiz)){
	    $authorID = $users->get($authorNameSanitiz);
			$p->createdUser->name = $authorID;
	  } else {
	    $u = new User();
	    $u->name = $authorNameSanitiz;
	    $u->addRole("author");
	    $u->addRole("guest");
	    $u->save();

			echo 'creat User: '. $authorName .'<br>';

			$authorID = $users->get($authorNameSanitiz);
	    $p->createdUser = $authorID;
	  }

	  $p->save();

	#}

  // populate fields
  //$p->images->add('path/to/image1.jpg'); // add multiple to images field
	$i++;
}

The CSV:

"Titel","Inhalt","E-Mail","Schlagworte","Thema","Benutzername","Beitragsdatum"
"digitale Filme in der Strahlentherapie","Hi,<br>zur Zeit suchen wir in unserer Abteilung für Strahlentherapie in Regensburg eine digitales Filmsystem.<br>Welche Firmen bieten den solche Systeme für die Strahlentherapie an?<br>MfG<br>Jan<br>","janmee@web.de","","Strahlentherapie","pete","1437587189"
"Gehalt MTA R","Hallo,<br>ich interessiere mich für den Beruf. Wo kann ich erfahren, was ich ausgelernt verdiene? Gibt es einen Tarifvertrag? In welchem ist man da wie eingruppiert? Vielen Dank<br> <br> <br> <br> <br> <br>","sweetmic@web.de","Gehalt","Radiologie","guest","1437303471"

what am i doing wrong?

Share this post


Link to post
Share on other sites

Quick response: 

For changing the user of a page try:

$p->created_users_id = $authorID;
$p->save(array('quiet' => true));

If you also want to set the modified user you may need to use some SQL, although I think quiet save works for this also in newer dev versions of PW:

$sql = "UPDATE `pages` SET `modified_users_id` = '".$authorID;."' WHERE `id` = '".$p->id."';";
$update = wire('db')->query($sql);

Keep in mind that if you find you need to use the SQL approach, it will need to be executed after the last saving of the page or it will be overwritten.

  • Like 1

Share this post


Link to post
Share on other sites

this line will not work I believe:

 $p->parent = wire('pages')->get('/$parent/'); //set the parent

'/$parent/' : if you use it with a variable as shown in your code, you must surround it with doublequotes: "/$parent/". Variables will not be populated within singlequotes.

------

Where is the code (line) where you check for existing records? Are there unique fields in your drupal data with the records that you can use?

steps to do:

1) read (next) record from drupal source

2) fetch and prepare data for a unique identifier from it

This can be a unique field within the drupal data, or, if this is not present, create a selector that may contain sanitized values for name / author / date or what is the best for your data.

3) do a get() with this selector

If the page exists, modify it where needed or move on to the next record.

If it do not exist, create it and populate fields.

  • Like 1

Share this post


Link to post
Share on other sites

Quick response: 

For changing the user of a page try:

$p->created_users_id = $authorID;
$p->save(array('quiet' => true));
....

Thanks, the first issue are solved!

The next Problem is to set the User i get following issue:

Notice: Object of class User could not be converted to int i

but the output of $authorID is a int ... 1370 or something else.

for testing i use this code:

$authorNameSanitiz = $sanitizer->name($authorName);
	$authorID = $users->get($authorNameSanitiz);
	if($authorID instanceof NullPage && $authorNameSanitiz != 'guest'){
		# Creat new User
		echo 'creat User: '. $authorName .'<br>';
	} elseif($authorNameSanitiz != 'guest') {
		echo "Existiert: " . $users->get($authorID)->name . " id= " . $authorID . "<br>";
	} else {
		echo "Gast <br>";
	}

Share this post


Link to post
Share on other sites

Try this:

$authorID = $users->get($authorNameSanitiz)->id;

You need to get the ID of the user, not the user object.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By maba
      Hello,
      I need to import regularly - every 15 or 30 days - a big .xslx file into my PW installation.
      This file now has 14 columns, 5.000 rows and grows every month.
      I'll need to group, order and work with these data to:
      analyse User monthly costs analyse User costs per Asset ... User (real AD account) has to match with a PW user - I can't join to the domain - but as you can see I have some services users (start with sca_*) or no user at all. Those rows have to be assigned to a specific user, e.g. account100.
      And:
      I would like to be able to have a kind of diff function to compare User assets between this and last month (and so on) other request is to have a notification when something change for a User between actual and latest import First request: which is the best solution to store those data in your opinion? Page, Table, Repeater Matrix, ...?
      Those are very repetitive data and I think a page reference is better than to import all the data every time but I have to understand how to manage those "dynamic" groups of software (AccType Det), hardware (Asset), ... For example Price will be imported and not stored with the description because it could be change in the future and I'll not have any control on it.
      Thanks!
      User,OE,productNmr,AccType1,AccType Det,Count,Price (€),Sum,ASNA,CC,AccType Info,Asset,AccGroup,,,,,,,,,,,,,
    • By dragan
      Is it by design that a site/ready.php is not included when creating a new site profile? Is it possible to include it with a hook? Or are there any security thoughts? (I don't want to redistribute it in public, it's just so I have my own boilerplate)
    • By karian
      I don't know why multiple instances (repeater_repeat_columns1, repeater_repeat_columns2, ...) of my repeater field are displayed inside Template field (see image).
      Is there a way to clean/reset it ?
       

    • By psy
      I'm combining two PW sites into one, Site A into Site B.
      At each step, I did it bit by bit as the 'all at once' approach failed.
       
      First, I exported all the fields from Site A and imported into Site B. Any field types not supported by import/export, eg FieldtypeOptions I manually recreated. All good.
      Next I exported all the templates from Site A and imported them into Site B and copied across their associated template files. All good.
      Finally I exported the pages I needed from Site A into Site B - again, bit by bit to ensure it all went smoothly.
      From the admin side, it all looked and worked perfectly.
      Front end was a totally different story. All existing pages in Site B worked as expected. NONE of the pages imported from Site A displayed. They all ended in a redirect loop with no errors in the PW logs or Tracy Debugger.
      After some trial-and-error, I finally got it working with:
      - create a new template in Site B admin with no associated template file and just a title field
      - import the fields from the imported Site A template into the newly created template (both on Site B)
      - copy the Site A php template file into a new file that matched the new PW Site B template name and save in Site B site/templates
      I can deal with the above workaround. Just curious to know if I did something wrong or if the template import/export feature is problematic?
       
      ### Solution:
      While the export/import was a slow process, turned out the front end redirecting issue was unrelated. For reasons unknown, all templates marked as HTTPS only were the ones redirecting, ie all templates from Site A. Finally solved it by changing the $config->https to true in site/config.php
      Now the pages display correctly as https whether the template forces the issue or not.
       
    • By dweeda
      How do I migrate a template with all its fields and values to a new site? Is their an export/import process?
×
×
  • Create New...