Fix generate_code, add onBeforeWrite for auto generating codes