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!
Add content programmatically to Umbraco 8
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 :
#umbraco friends - @HotChilliCode made a suggestion today about programmatically creating a load of content in to the backoffice to aid testing - anyone done this and got examples or is it documented? #lateNightCoding— Owain Williams (@ScottishCoder) October 12, 2020
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:
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!
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.