When building websites for clients, we find ourselves in the position of needing to enter a lot of dummy content. This allows us to test pagination, search results and a number of other features which can be time-consuming. Thankfully, we’ve got a method of creating this content for our Umbraco websites.
We asked Owain Williams, our Umbraco 3x MVP and Master for his top tips on programmatically adding content to Umbraco 8.
Over to you Owain!
If there’s a need for adding a lot of data to a project to allow test pagination and filtering, previously, I would’ve added each content node manually. But, Nick suggested I script it to be reused for other parts of the project, too which sparked my thinking… how the heck would I do this and where do I begin?
Looking at the Umbraco Documentation, I spotted I could potentially use the Content Service in Umbraco 8… but that was as far as I got! My next attack was looking at building a backoffice package or dashboard but quickly realised I was overthinking and overcomplicating things. At this point, I called on the Umbraco Community for ideas.
Enter Paul Seal, who very kindly shared this code with me:
It took a few small tweaks 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, would make each node name more unique. Without this array, the node names are simply copied and (0), (1), (2), is just appended to the end of the name.
Things to do before you run the code
You’ll need to have a parent folder setup with a single child beneath it in the backoffice:
Explaining the code
You’ll need to drop the code into a page that can e loaded from the front end. I chose to put in a partial that isn’t used on any other pages. You could also put it on a hidden page or a Masterpage too, the choice is yours.
The `parentNodeToCopy` value is the id of the September folder. In this case, 3625.
Now the code will have made a copy of the content that’s in this folder. But, you’ll need to be careful because the for loop can go wild! Start it with one item which will be duplicated and then you’ll have 2 times, next time the loop goes around, it’ll go from 2 to 4 items. I may have made the mistake of putting the for loop to 10…
2, 4, 8, 16, 32, 64, 128, 256, 512, 1024.
That’s how I ended up with 1025 items under my September folder! I deleted everything reworked it.
In the image above, you’ll see how I have 4 items with random names from the array of strings. Each one has been saved and published.
Huge thanks to Paul for sharing this code, the original few lines of code saved me loads of time and I hope this blog helps others in future!
For more from Owain, you can check out his blog, Owain Codes, here.
If you’d like to get started on your Umbraco journey with Spindogs, why not get in touch below? We’d love to hear from you!