0

I need help on to correct my implementation on validating the email if it's already exists.

Anyone knows what's wrong with my code? It is not validating this part. It will save even if the email already exists in db.

 if ($existingFeedback->getId()) {
            $result = ['success' => false, 'error' => __('Email already exists in the database.')];
            $this->getResponse()->setBody(json_encode($result));
            return;
        }

public function execute()
    {
        $data = $this->getRequest()->getPostValue();

        if (!$data) {
            $this->_redirect('*/*/');
            return;
        }

        // Validate email
        if (empty($data['email'])) {
            $result = ['success' => false, 'error' => __('Email is required.')];
            $this->getResponse()->setBody(json_encode($result));
            return;
        }

        // Check if email already exists
        $existingFeedback = $this->customerFeedbackFactory->create()->getCollection()
            ->addFieldToFilter('email', $data['email'])
            ->getFirstItem();


        if ($existingFeedback->getId()) {
            $result = ['success' => false, 'error' => __('Email already exists in the database.')];
            $this->getResponse()->setBody(json_encode($result));
            return;
        }

        $customerFeedback = $this->customerFeedbackFactory->create();
        $customerFeedback->setData('title', $data['title']);
        $customerFeedback->setData('content', $data['content']);
        $customerFeedback->setData('email', $data['email']);
        $customerFeedback->save();

        $result = ['success' => true];
        $this->getResponse()->setBody(json_encode($result));
    }

2 Answers 2

0

the correct one is this:

 $existingFeedback = $this->customerFeedbackFactory->create()->getCollection()
            ->addFieldToFilter('email', $data['email'])
            ->getSize();
0

If you are using the custom module for validating the email on saving you can also validate using the Repository as well.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.