I've been trying to figure out the best way to hook in and replace the title of my variations in code when they're saved. What I'd like to do is have it generate an automatic title, but change something about that title from another module in code automatically.
The problem is that we have some "N/A" attribute values, and the auto titles are ugly because they have sometimes repeated "N/A, N/A" values in their titles, and our client doesn't want those there (and I can understand why). Since their products are so varied that we can't really get around some attributes not applying to some products, and since attribute fields require a value, the N/A value was the way around that. it seems the only real way around the title issue is to override the variation titles and remove those N/A values.
I've tried ProductEvents::PRODUCT_VARIATION_INSERT and ProductEvents::PRODUCT_VARIATION_UPDATE but trying to set the title there simply has no effect, it gets overridden after that again if I have automatic titles enabled.
Is there a later hook I should use, or another recommended way that I could achieve the desired effect of modifying the auto-generated variation title (automatically, every time a variation is saved)?
Issue fork commerce-2846895
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #2
replicaobscuraComment #3
replicaobscuraHere's a simple approach that dispatches a new event after generating the title, before saving it, to allow it to be overridden:
https://github.com/drupalcommerce/commerce/pull/707
https://github.com/drupalcommerce/commerce/pull/707.patch
Comment #4
replicaobscuraI haven't had time to create tests for this yet, though the patch still does work well for me in the latest commerce versions.
Comment #5
cosolom commentedYou can use hook_presave if you will uncheck "Generate variation titles based on attribute values" and move part code for generate title in your custom hook_presave.
Comment #6
replicaobscuraI think that would be a possibility, but the auto-generated titles are often useful and may just need to be customized like in my case.
Comment #9
scottsawyerUpdating target branch.
Comment #13
scottsawyerHm, there is a test failure https://git.drupalcode.org/issue/commerce-2846895/-/jobs/6267257
I am not sure how that is related. There's one coding standards issue, easily fixed.
Comment #14
jsacksick commentedOk, I'm not against the idea.
Can we please address the feedbacks I gave in the MR? Let's use property promotion in the event constructor.
Let's pass the variation first, then the title and also define return types for methods.
Comment #15
jsacksick commented