Skip to the content

Add content programmatically to Umbraco 8

First of all, I can't take any credit for this code. I have kindly been given permission to share it with you by Paul Seal from codeshare.co.uk.

I had the requirement to add a lot of data in to a project so that I can test pagination and filtering. In the past, I would add each content node manually but Nik suggested I script it so it can be reused for other sections of the project we are working on. 

This got me thinking. How the heck would I do this and where would I start? 

I had a look at the Umbraco Documentation and spotted I could maybe use the Content Service in Umbraco 8 but honestly, that was as far as I got. I started thinking about building a backoffice package or dashboard, basically over thinking things, when I saw over thinking, I actually got myself in to a pickle so turned to the Umbraco Community.

I put a tweet out : 

 

A number of people had done something very similar but unfortunately didn't have any code examples. 

Paul to the rescue. 

He kindly shared the following code with me: 

I edited it slightly to add the array of strings so that the node names and titleHeadingOne property, which is the property alias of a textstring on the node. This makes each node name bit more unique. Without this array, the node names are copied and (0), (1), (2), is just appended to the end of the name.

 

Before you run the code

In the backoffice, you need to have a parent folder setup with a single child beneath it:

Before running the code

The code explained

This code is dropped in to a page that you are able to load from the front end, I put it in a partial that is only used on a specific page. You put it on a Masterpage or a hidden page somewhere, it's really up to you. 

The `parentNodeToCopy` value is the id of the September folder. In this case, 3625.

What the code now does is makes a copy of the content within this folder. This is when you need to be careful, the for loop can really go crazy. You start with 1 item which then duplicates and now you have 2 times, the next time the loop goes round, you go from 2 to 4 items. I made the mistake of putting the for loop to 10. 

 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024.

Yip, I ended up with 1025 items under my September folder! I deleted everything and dialled it back! 

Folder content after running the code

You can now see I have 4 items with random names from the array of strings and each one has been saved and published. 

 

Thanks Paul for sharing this code with me, the original 10 or so lines of code saved me a lot of time and I hope this blog helps others in future. 

 

About the author

Owain

Owain

Owain is an Umbraco MVP, an Umbraco certified master and works on Umbraco projects on a daily basis. When not coding, he enjoys running, spending time with his wife and building lego! 

He is also a GitKraken ambassador and helps look after the H5YR.com website.

comments powered by Disqus