I was offering Sunnah prayer in the mosque, after the congregation prayer was over, when a man came and joined me. I changed my intention for his sake and made my prayer the obligatory one. When we finished, I started offering Sunnah again, when another man came and did the same. I did not change my intention this time and completed my prayer as usual. Please comment on my action on both occasions.

There is no harm in a person offering a Sunnah prayer being the imam of another person who is offering an obligatory prayer. This happens all the time, particularly in Ramadhan, when people who come late into the mosque, when the imam has started taraweeh while they have not prayed Isha yet. They continue with their prayer and the Imam continues with his. Both are valid and acceptable. So, when you continued with your Sunnah the second time and the other person prayed his obligatory prayers, both of you were correct and both your prayers were valid.

This first case is different because it involved a change of intention on your part. Such a change makes your prayer invalid, because you abandoned a prayer, which you had started and began another without fulfilling its essentials. For example, you start a prayer with takbeer but you have not done that, thinking that the one you did for your Sunnah was sufficient. How could it be when it was not meant for it? You need to repeat that prayer. As for the other person, his prayer is acceptable, God willing.