The formula of an ionic compound is determined by the charges on the ions. Because electrons are being transferred in an ionic compound, we need to make sure the number of electrons lost from the cation equals the number of electrons gained by the anion. Additionally, for the number of electrons gained and lost is based on how the number of valence electrons differs from the number of valence electrons in the nearest noble gas.
For example, Na has 1 valence electrons and will lose 1 electron to become a cation with a +1 charge. While Mg, will lose 2 electrons to become a cation with a +2 charge because it has two valence electrons. We can look at a similar approach for anions but will gain electrons instead of losing electrons. For example, oxygen has 6 valence electrons and will gain two to become an anion with a -2 charge. For polyatomic ions, they have a set charge (i.e. PO4^3-, phosphate). In this case, we can treat the polyatomic ion the same way we would look at a monatomic ion.
For sodium phosphate, we know that sodium goes to Na+1 and phosphate is PO4^3-. In order for the number of electrons gained and lost to be equal, we need three Na+1 cations to pair with one phosphate (PO4^3-) ion which results in the formula Na3PO4 for the compound.