Please upgrade here. These earlier versions are no longer being updated and have security issues.
HackerOne users: Testing against this community violates our program's Terms of Service and will result in your bounty being denied.

Create new discussion on registration

Hello there !

As a new user, I hope it's the right place to ask questions about vanilla but please tell me if I'm wrong.

What I'd like to achieve is quite simple to explain, when a person registers on my website, I have a custom registration form which I can describe as follows :

  • Name [username]
  • Password
  • Age [userage]
  • Why do you wanna join the community ? [reason]

Now, when the registration process is completed, it'd would be awesome to have vanilla create a new discussion under a certain category, lets say "new users", and format it. It could be like :

  • Discussion Title : New user ! Welcome [username]
  • Discussion Content :
    Please all welcome [username] !
    [reason]

I've already made some research on the subject, and found some interesting topics but nothing really clear ...

Any help would be really appreciated :) !

Thx a lot !

Cheers

«1

Comments

  • Create a plugin, hook into the registration event, and submit a new discussion.

    public function userModel_afterRegister_handler($sender) {
        $userID = $sender->EventArguments['UserID'];
    
        $user = $sender->GetID($userID);
        $discussionModel = new DiscussionModel();
        $discussionModel->Insert(array(
            'CategoryID' => '-1',
            'InsertUserID' => '2',
            'Name' => 'This is the title',
            'Body' => 'This is a body',
            'CountComments' => '0',
            'CountViews' => '1',
            'Closed' => '0',
            'Announce' => '0',
            'Sink' => '0',
            'DateInserted' => '2015-07-30 00:00:00'
        ));
    }
    

    Search first

    Check out the Documentation! We are always looking for new content and pull requests.

    Click on insightful, awesome, and funny reactions to thank community volunteers for their valuable posts.

  • MrVladMrVlad New
    edited July 2015

    wow ! Thanks for that quick and helpful answer :D !

    My plugin is set and ready, I have just a couple more questions if you don't mind (I think I can handle that myself but you'll sure be way more competent than me).

    Is there a simple way to access IDs for categories ? I understand I have to adapt the code you sent me with the right CategoryID (I'm reading the community wiki right now to find any useful information about that).
    Forget that I'll get them from the database (silly me)

    Another issue, i can activate the plugin ... but when it's on i can't turn it off. I tried to add an "empty" plugin (which doesn't do anything) and the issue still remains.

    Anyway, thx again for your help, that's very kind !

  • The quickest way to find a category ID is click to edit it in the dashboard and look at the URL. You can also just hover over the edit link in the category management screen.

    http://forums.example.com/vanilla/settings/managecategories

    Search first

    Check out the Documentation! We are always looking for new content and pull requests.

    Click on insightful, awesome, and funny reactions to thank community volunteers for their valuable posts.

  • MrVladMrVlad New
    edited July 2015

    Everything is working fine now (I just have to fix the on/off issue) ! Sir, you're a real gentleman ! Thank you very much !

    Would it be useful for the community, once I've polished the plugin, to release it in the add-ons section ? (or maybe nobody cares ^^).

    Cheers !

  • LincLinc Admin

    This is a brilliant plugin idea.

  • R_JR_J Admin
    edited July 2015

    See if the plugins name in the PluginInfo array ($PluginInfo['...'] = array() is the same as in the class (class ...Plugin extends Gdn_Plugin {). That is most often the cause for not being able to deactivate a plugin ;)

  • thx for the tip ! Unfortunately it was already the case :/ ... @Linc, I'll publish it as soon as it is done then !

  • o:) back again ... With a couple more questions !

    In your opinion, which method is the most appropriate to access user data ? For example, if my goal is to extract UserName or other infos in order to parse them in the post I want to create, are there vanilla functions which can help me ?

    I might sound ... well quite dumb actually, but my php isn't my biggest stenght :/

    I had a look on class.usermodel.php and I'll keep reading the community wiki of course !

  • Use the user object loaded on line 4 of my example. Either inspect it with your debugger or var_dump it.

    Search first

    Check out the Documentation! We are always looking for new content and pull requests.

    Click on insightful, awesome, and funny reactions to thank community volunteers for their valuable posts.

  • peregrineperegrine MVP
    edited July 2015

    Another issue, i can activate the plugin ... but when it's on i can't turn it off. I tried to add an "empty" plugin (which doesn't do anything) and the issue still remains.

    Is the plugin folder name exactly the same as in $PluginInfo['...']

    by case.

    e,g,

    Uppercase is not the same as uppercase or upperCase

    If you can't turn off other enabled plugins you didn't create it could be caching problem

    but the only time I have seen people able to activate but not deactivate plugins is when the folder didn't match the plugin name or when they had duplicate old folders of the same plugin and mistakenly didn't clean up old junk and weren't acting upon what they thought they were.

    I may not provide the completed solution you might desire, but I do try to provide honest suggestions to help you solve your issue.

  • ... there was a typo in the plugin folder name, which of course I did not see before your answer (every time I ask for help anywhere I always realize how stupid I can be ^^).

    Thx for the tip @hgtonight, I'll look for some info on user object in the wiki then !

  • Hi there :) !

    Made some sweet progress during the week end ! Thx to @hgtonight , I used the user object to retrieve UserName and it now works like a charm !

    I'm considering adding new fields in the registration form, and for now I'm using the addon Profile Extender as @Linc suggested in many other discussions. I'd like to get that info when the registration is done and display it in the new discussion as well.

    There are a few topics with different methods, but I was thinking to use something like this :

    // Get additionnal info (using profile extender)
    $userMeta = Gdn::UserMetaModel()->GetUserMeta($userID, 'Profile%');
    $userHobbies = val('Profile.hobbies', $userMeta);
    

    For now, I've added a field "hobbies" (dropdown selector) and it sucessfully display the selectd hobby on the profile page. However, $userHobbies remains empty in my function.

    Do you think it's the right way to retrieve the data, or should I use another method ?

    Thx a lot, as usual :) !

  • Ok ... JUST one more question, I swear :p !

    I'm having trouble with "DateInserted" for the new discussion. I'm using :

    // Get date
    $date = Gdn_Format::ToDateTime();

    then :

    // Set inserted date for discussion
    'DateInserted' => $date

    .... and it works ! Well actually not really :/ ... the new discussion is correctly added (I checked the database to see that everything is fine), but no date is displayed on the forum ! And as usual, I'm sure that I've been missing a tiny thing for a couple of hours now, but I can't figure what it is!

  • mtschirsmtschirs ✭✭✭
    edited August 2015

    Add a comment to the discussion and check back if the date is now displayed. If yes, it might be related to vanillaforums.org/discussion/30496/issue-recent-discussions-module-doesnt-show-author

  • The issue remains, even when adding a new comment ... BUT, I tried to upload the plugin on my server (I was using a locale installation to test before that) ... and now, everything works ... I'm lost in a sea of madness.

    And of course, the issues I managed to fix with profile extender are now back on track and I can't figure why, this is driving me insane !

    thx for your help anyway, you guys are very kind :) !

  • x00x00 MVP
    edited September 2015

    look at applications/vanilla/settings/stub.php for an example

    grep is your friend.

  • So ... the situation was pretty much fubar with my plugin and I decided to start over.

    Again, I could use your advice on a couple of questions that I have ... If you did not read the previous posts, I'd like to add new fields on registration for users to fill, then use this data to create a new discussion on the forum in order to make a "presentation post" automatically.

    The second part is done and works fine. The first however, is causing me great trouble. I initially thought of using Profile Extender as a way to create and extract new data fields during registration, but for an obscure reason, it doesn't work for me ... at all ... nope ... no way ... tried everything.

    What method would you use to create a form, display it on the registration page, extract its data when registration is complete and parse it into a discussion ?

    Btw, I don't need to "keep" the data, once the registration is done, it can be deleted, flushed or whatever ...

    thx for any help :) !

  • If you do not need the data and your only profile-extender-problem is that the fields are not prefilled later on, I still would stick to the profile extender. Only check "required" and "show on registration" but leave "show on profile" unchecked.

    You can then use public function entryController_RegisterValidation_handler($sender) { to access the new fields. And I would store them in UserMeta Gdn::userMetaModel()->setUserMeta($userID, 'Profile.'.$fieldname, $value); manually. This way you imitate the profile extender which makes it easier to stay compatible with the ProfileExtender plugin (which will work).

    You'll then be able to access that value like this:

    $profileFields = Gdn::userMetaModel()->getUserMeta($userID, 'Profile.%', 'Profile.');
    $value = $profileFields['Profile.'.$fieldname];
    

    If something is not working as expected, simply share some code.

    If you really don't want to use the Profile Extender, you could use

    public function setup() {
      $this->structure();
    }
    
    public function structure() {
      Gdn::database()->structure()
        ->table('User')
        ->column('YourFieldName', 'varchar(64)', '')
        ->set();
    }
    
    public function entryController_extendedRegistrationFields_handler($sender, $args) {
     // or use RegisterFormBeforeTerms
      echo '<li>';
      echo $this->Form->label('Text to display', 'YourFieldName');
      echo $this->Form->textBox('YourFieldName');
      echo '</li>';
    }
    
  • @R_J : i used public function entryController_RegisterValidation_handler($sender) as you suggested and was able to retrieve the values I needed. Then I realized I had to use public function userModel_afterRegister_handler($sender) to get user data and create a discussion, as @hgtonight told me some time ago ... therefore, I created some Globals to store the info and pass it from one function to the other ... and it's working :D ! THX !!!

    Here is my code, ugly and raw, but I'll clean it during the next few days. Do you think that this could be a good addition to the plugin database ? If so, I'll try to create a admin interface and publish it ...

    <?php if (!defined('APPLICATION')) exit();
    
    $PluginInfo['postonregister'] = array(
        'Name' => 'Post on register',
        'Description' => 'Create a new post each time a new user registers',
        'Version' => '0.1',
        'Author' => 'Vladvonvidden',
    );
    
    // Globals
    $var = "Aucun";
    $quelJeu = "Aucun";
    $comment = "Par Internet";
    $plusSurVous = "je suis quelqu'un de distrait";
    
    class postonregister extends Gdn_Plugin {
    
        public function entryController_RegisterValidation_handler($sender) {
            $GLOBALS['var'] = $sender->Form->_FormValues['Aqueljeujouezvousgalement'];
            $GLOBALS['quelJeu'] = $sender->Form->_FormValues['Pourqueljeupostulezvous'];
            $GLOBALS['comment'] = $sender->Form->_FormValues['CommentavezvousetconnaissanceduConsortiumHorizon'];
            $GLOBALS['plusSurVous'] = $sender->Form->_FormValues['Ditesnousenplussurvous'];
        }
    
        public function userModel_afterRegister_handler($sender, $Args) {
            // Get user ID from sender
            $userID = $sender->EventArguments['UserID'];
            // Retreive user object
            $user = $sender->GetID($userID);
            // Get UserName
            $name = GetValue('Name', $user, $Default = FALSE, $Remove = FALSE);
            // Get first visit date
            $date = Gdn_Format::ToDateTime();
            // Create new discussionModel
            $DiscussionModel = new DiscussionModel();
            // Feed it ! Feeeeeeeeed it !
            $SQL = Gdn::Database()->SQL();
            // Where you wanna insert the discussion (which category)
            $Discussion['CategoryID'] = '9';
            // Discussion Format (BBcode)
            $Discussion['Format'] = 'BBCode';
            // Discussion title
            $Discussion['Name'] = '[' . $GLOBALS['quelJeu'] . '] ' . (string) $name . ' [En attente de validation]';
            // Discussion content
            $Discussion['Body'] = '[b]Pour quel jeu en particulier postulez-vous dans la Guilde ?[/b]
    
            '
            . $GLOBALS['quelJeu'] .
            '
    
            [b]A quels autres jeux jouez-vous également ?[/b]
    
            '
            . $GLOBALS['var'] .
            '
    
            [b]Comment avez-eu connaissance du Consortium Horizon ?[/b]
    
            '
            . $GLOBALS['comment'] .
            '
    
            [b]Dites-en un peu plus sur vous :[/b]
    
            '
            . $GLOBALS['plusSurVous'] .
            '
    
            En attente de validation par un modérateur';
            // Date of creation
            $Discussion['DateInserted'] = $date;
            // Date of last comment
            $Discussion['DateLastComment'] = $date;
            // The author
            $Discussion['InsertUserID'] = $userID ;
            // Insert in the right category
            $DiscussionID = $SQL->Insert('Discussion', $Discussion);
            // If everything is ok, refresh discussion count
            if ($DiscussionID) { $DiscussionModel->UpdateDiscussionCount($Discussion['CategoryID']) ;}
        }
    }
    
Sign In or Register to comment.