2

Post Response

form.components.ts

OnSubmit(form : NgForm){

    this.userService.addUser(form.value).subscribe((data : any)=> {

        if(data.Succeeded ==true){
            console.log("Sent");
        }
    });
}   

user.service

addUser(user: User){
    const body: User = {
        UserName: user.UserName,
        Password: user.Password,
        Email: user.Email,
        FirstName: user.FirstName,
        LastName: user.LastName
    }

    return this.http.post(this.url , body);
}

I'm new to angular and Symfony.. I haven't seen much tutorial about how to do the above operation. In above code I'm sending data over API to symfony from Angular 5. My question is how to get all the data from the api and insert into mysql.

1
  • The action form of your form should point to your api in symfony. Have you a controller in your Backend symfony side? Can we see it? Commented Feb 16, 2018 at 8:30

1 Answer 1

2

There are many ways in Symfony to achieve this. I will assume that you use a basic Symfony stack with Doctrine as ORM, that your entities are already created, and that you already have a controller having a Request argument.

The optimized way

You first need to deserialize the Response with the Serializer service. If the response is valid, you will get an object of your User entity filled with your request data.

Then, use the entity manager to persist data into your database.

You can also use some validation to validate data before persisting, and return errors if needed.

With Autowiring and Autoconfigure, all your controllers will be registered as services, and all your dependancy will be injected. So you can just do :

class AcmeController extends Controller
{
      private $serializer;
      private $entityManager;

      public function __construct(Serializer $serializer, EntityManager $entityManager) {
             $this->serializer = $serializer;
             $this->entityManager = $entityManager;
      }

      public function myAction(Request $request) {
             $user = $this->serializer->deserialize($request->request->all(), User::class, 'json');
             /** validate your data, the $user will be false if the serializer encountered an error **/

             $this->entityManager->persist($user);
             $this->entityManager->flush();

             /** Return whatever Response object you need **/
      }
}

Without autowiring and autoconfigure, you can just use the get() function and the getDoctrine() shortcut of the Controller class :

class AcmeController extends Controller
{
      public function myAction(Request $request) {
             $user = $this->get('serializer')->deserialize($request->request->all(), User::class, 'json');
             /** validate your data first, the $user will be false if the serializer encountered an error **/

             $this->getDoctrine()->getManager()->persist($user);
             $this->getDoctrine()->getManager()->flush();

             /** Return whatever Response object you need **/
      }
}

The "easy" way

You can also use forms. Create a form corresponding to your User entity.

Something like this should do the trick. However, be careful to the name of the fields. If your API fields name do not correspond to your entity fields name, you may need to use the property-path option.

class UserForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('LastName')
            ->add('FirstName')
            ->add('password', PasswordType::class)
            ->add('Email', EmailType::class)
            ->add('UserName')
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

Then, in your controller, submit it and persist your data :

class AcmeController extends Controller
{
      public function myAction(Request $request) {
             $user = new User();
             $form = $this->createForm(UserType::class, $user);
             $form->handleRequest($request);

             if ($form->isSubmitted() && $form->isValid()) {
                   $this->getDoctrine()->getManager()->persist($user);
                   $this->getDoctrine()->getManager()->flush();

                   /** Return whatever Response object you need **/
             }

             // get errors
             $errors = $form->getErrors();

             /** Return whatever Response object you need **/
      }
}

As i said, the first way is more optimized, as Form objects will be created in the "easy" way and are kind of big. However, it is much harder to use and understand it when you are a new comer.

Use the one you are comfortable with.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.