2

I'd like to be able to create a Sprout Forms entry from another plugin I'm working on. Is this possible?

I had a bit of a look at the SproutForms_EntriesController->actionSaveEntry() action but it's kind of all bundled up.

This other plugin is a self contained booking system that I don't want to use an actual Sprout Forms form for - but to keep it consistent for the client I'd like to write (for reference) these entries into a pre-existing form I've set up.

Thanks!

3

When leveraging another plugin programmatically, you will typically want to use the service layer. In your case, the SproutForms_EntriesService.php is where the saveEntry action gets processed. The saveEntry service method expects a SproutForms_EntryModel:

craft()->sproutForms->saveEntry($entry);

Here is a longer example:

// Create a new instance of a SproutForms_EntryModel
$entry = new SproutForms_EntryModel();

// Set some SproutForms_EntryModel attributes
$entry->formId    = 4051;
$entry->ipAddress = '127.0.0.1';
$entry->userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36';

// Set the custom fields
$entry->setContentFromPost(array(
    'fullName' => 'Test Name',
    'message' => 'Test message'
));

// Save the entry
craft()->sproutForms_entries->saveEntry($entry);

Sprout Forms should dynamically set the title value for you, based on the value you have in the Advanced->Title Format setting.

In the case it doesn't seem to work, a quick way to see if there are any errors is to kill your script after you tried to save the entry and view the full list of errors (or use a more advanced PHP debugging workflow with a tool like XDebug):

Craft::dd($entry->getErrors());

See the answer from Brandon Kelly on this post for more information on how to set custom fields on an Element.

  • Thank you for the comprehensive answer Ben :) fantastic. I'll give it a try and mark it as correct then. – JamesNZ Dec 4 '16 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.