How do I insert logic for the Table of Contents?

Not exactly what you want, but you may get some inspiration from this: