General developer forum

Generate new ID coursemodule

Picture of Daniel Garcia
Generate new ID coursemodule



I want to generate a new ID coursemodule from PHP code. Let me explain better:

Imagine you have three activities in a course. So, the next activity will have coursemodule ID '4'. I want to add the coursemodule ID by PHP code not with Moodle interface.

How could I do?


Thanks in advance.




Average of ratings: -
Re: Generate new ID coursemodule

Why would you want to do that? Do you mean the id that's displayed in the url, e.g.:

And now you'd like to specify which id is used for a newly added activity?

Generally speaking all ids are generated by the database server. It would be dangerous to change these ids, as they may have been used in other tables.

The only ids that you can safely change are exactly the ones that are accessible through Moodle forms. But those are ids are typically not the coursemodule ids.

Average of ratings: -
Picture of Gordon Bateson
Re: Generate new ID coursemodule
Core developersParticularly helpful MoodlersPlugin developersTranslators

as Onno says, it is usually better to use the Moodle API (i.e. the $DB object and the functions in "course/lib.php") to manipulate the Moodle database, even if you are not using the Moodle user-interface.

For example if you want to add a new course module record, you must remember to also add a "context" record, and to insert the new course module id in the appropriate place of the "sequence" field of the the appropriate "course_sections" record. Phew!

However, if you are determined to do it without the Moodle API, then all you need to do is run an SQL "insert" query without the "id" field set. The id will be set automtically for you (by the database). You can find out what it was set to, if you use the appropriate command for your database. For example, for MySQL you would use the "LAST_INSERT_ID()" command. If you are programming in PHP, you can use PHP's "mysql_insert_id()" function.

good luck!

Average of ratings: -
Picture of Mike Churchward
Re: Generate new ID coursemodule
Core developersParticularly helpful MoodlersPlugin developersPlugins guardiansTesters

Your request is a little "cloudy"... But if what you are trying to do is to have something outside of Moodle create new activities in a course, consider using the web services API. You may have to write the services you need, but maybe not.


Average of ratings: -