Hi everyone!
I have been wondering is it possible to export for translation modal data i have set that modal data is translatable like this but would it be possible to somehow export all of that translatable file data to csv in similar way that messages are done.
public $implement = [
\RainLab\Translate\Behaviors\TranslatableModel::class
];
public $translatable = [];
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
// Get all fields from the database table
$tableColumns = $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
// Exclude non-translatable fields, such as primary key, timestamps, etc.
$translatableFields = array_diff($tableColumns, ['id', 'created_at', 'updated_at']);
// Assign translatable fields
$this->translatable = $translatableFields;
}
Well yes it adds that and works but it’s super cumbersome to add translations as you need to open a record edit save switch language edit save. It would be better to get a csv with all plugin dynamic data and do translations.
You can read and update model data from a CSV file programmatically. For details on translating model data, refer to the RainLab Translate Plugin documentation.
Let’s suppose we have that we have a CSV that looks like this :
id,name_fr,name_en,description_fr,description_en
1,pomme,apple,pomme rouge croquante,crunchy red apple
Here’s a practical example using a CSV file (not tested but that is the idea):
// Path to the CSV file
$csvFile = 'path/to/products_translated.csv';
// Open the CSV file for reading
if (($handle = fopen($csvFile, 'r')) !== false) {
// Get the header row
$headers = fgetcsv($handle);
while (($row = fgetcsv($handle)) !== false) {
// Map row data to headers
$rowData = array_combine($headers, $row);
// Find the product by ID (assuming 'id' is a column in your CSV)
$product = Product::find($rowData['id']);
if ($product) {
foreach ($rowData as $column => $value) {
// Use a regular expression to match column names that end with an underscore followed by a language code
if (preg_match('/_(\w+)$/', $column, $matches)) {
// Extract the language code from the column name
$languageCode = $matches[1];
// Extract the base attribute name from the column name
$attributeName = strstr($column, '_', true);
// Set the translated attribute for the detected language
$product->setAttributeTranslated($attributeName, $value, $languageCode);
}
}
// Save the product to persist the changes
$product->save();
}
}
// Close the file handle
fclose($handle);
} else {
echo "Error opening the file.";
}