Is this the correct approach?
The code shown in the question needs to be first fixed: In the foreach()
loop, it does not set $options[$key]
to any value read from the file because it does not use $value
.
Supposing that the options.txt file is contained in the same directory containing the .module file, the code to get the file path is the one shown by @4uk4.
The code you should use for selectlist_options()
becomes the following one.
function selectlist_options() {
$options = [];
$result = file('options.txt');
foreach ($result as $key => $value) {
$options[$key] = $value;
}
return $options;
}
On Drupal, strings used in the user interface must be translatable, while strings read from a file are not translatable. Furthermore, the files in the directory containing modules cannot be altered by the web server nor PHP. This means that, if the options.txt file is in the directory containing the module, its content is probably changed when the module is updated.
Instead of using a text file that is updated when the module is updated, it would be better to set directly the options with the code that initializes $form['mymodule_select']
. In this case, the options would be translatable too.