1

I would like the user to be able to manually enter the date that will be saved to the database. My MonthType looks like:

class MonthType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
    $builder->add(
        'name',
        TextType::class,
        [
            'label' => 'label.name',
            'required' => true,
            'attr' => [
                'max_length' => 128,
            ],
        ]
    );
    $builder->add(
        'dateStart',
        DateType::class,
        [
            'label' => 'label.dateStart',
            'format' => 'yyyy-MM-dd',
        ]
    );
    $builder->add(
        'dateEnd',
        DateType::class,
        [
            'label' => 'label.dateEnd',
            'format' => 'yyyy-MM-dd',

        ]
    );
    $builder->add(
        'upper_limit',
        MoneyType::class,
        [
            'label' => 'label.upper_limit',
            'currency' => false,
            'required' => true,
        ]
    );
    }
} 

My controller looks like:

class MonthController implements ControllerProviderInterface
{

    public function connect(Application $app)
    {
        $controller->match('/add', [$this, 'addAction'])
            ->method('POST|GET')
            ->bind('month_add');

        return $controller;
    }
    /**
    * Add action.
    */
    public function addAction(Application $app, Request $request)                               
    {
        $month = [];
        $userRepository = new UserRepository($app['db']);

        $token = $app['security.token_storage']->getToken();
        if (null !== $token) {
            $user = $token->getUser();
            $userLogin = $user->getUsername();
        }

        $form = $app['form.factory']->createBuilder(MonthType::class, $month)->getForm();
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $monthRepository = new MonthRepository($app['db']);
            $monthRepository->save($form->getData(), $userLogin);

            $app['session']->getFlashBag()->add(
                'messages',
                [
                    'type' => 'success',
                    'message' => 'message.element_successfully_added',
                ]
            );

            return $app->redirect($app['url_generator']->generate('month_index'), 301);
        }

        return $app['twig']->render(
            'history/add.html.twig',
            [
                'month' => $month,
                'form' => $form->createView(),
                'user_id' => $userRepository->findUserId($userLogin),
            ]
        );
    }
}

And in repository I have:

/**
 * Save record.
 */
public function save($month, $userLogin)
{
    $user_id = $this -> findUserIdByLogin($userLogin);
    $month['user_id'] = $user_id;
    $month['remained'] = $month['upper_limit'];

    if (isset($month['id']) && ctype_digit((string) $month['id']) && isset($user_id)) {
        // update record
        $id = $month['id'];
        unset($month['id']);

        return $this->db->update('month', $month, ['id' => $id]);
    } else {
        // add new record
        return $this->db->insert('month', $month);
    }
}

When I try to save record I get an error: An exception occurred while executing 'INSERT INTO month (name, dateStart, dateEnd, upper_limit, user_id, remained) VALUES (?, ?, ?, ?, ?, ?)' with params ["june 2012", {"date":"2012-06-01 00:00:00.000000","timezone_type":3,"timezone":"Europe/Berlin"}, {"date":"2012-06-30 00:00:00.000000","timezone_type":3,"timezone":"Europe/Berlin"}, 7600, "1", 7600]:

Catchable Fatal Error: Object of class DateTime could not be converted to string

So I tried to make something like that:

    public function save($month, $userLogin)
    {
        $user_id = $this -> findUserIdByLogin($userLogin);
        $month['user_id'] = $user_id;
        $month['remained'] = $month['upper_limit'];

        $dateStart = new \DateTime($month['dateStart']);
        $month['dateStart'] = $dateStart->format('Y-m-d');
        $dateEnd = new \DateTime($month['dateEnd']);
        $month['dateEnd'] = $dateEnd->format('Y-m-d');
        ...//
    }

but I received: DateTime::__construct() expects parameter 1 to be string, object given

2
  • whqt is your $month['dateStart'] ? have you dumped it ? isn't it a datetime object yet ? Commented Aug 3, 2017 at 14:48
  • dump($month['dateStart']) gives this DateTime {#678 ▼ +"date": "2012-01-01 00:00:00.000000" +"timezone_type": 3 +"timezone": "Europe/Berlin" } Commented Aug 5, 2017 at 15:32

2 Answers 2

1

Seems that you have both $month['dateStart'] and $month['dateEnd'] as DateTime (look at database exception {"date":"2012-06-01 00:00:00.000000","timezone_type":3,"timezone":"Europe/Berlin"}).

So you can use directly as $dateStart or $dateEnd as it:

$month['dateStart']->format('Y-m-d')

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

3 Comments

Thanks for your answer. I tried this one, but it gives the same error as without my modification.
have you tried by new DateTime($month['dateStart']->format('Y-m-d')?
Yes. No change.
1

I solved this problem. I used this: http://symfony.com/blog/new-in-symfony-3-1-datetime-normalizer and wrote

$serializer = new Serializer(array(new DateTimeNormalizer('Y-m-d')));
$month['dateStart'] = $serializer->normalize($month['dateStart']);
$serializer = new Serializer(array(new DateTimeNormalizer('Y-m-d')));
$month['dateEnd'] = $serializer->normalize($month['dateEnd']);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.