Is it possible to push data from 1 form to 2 tables(controller) cakephp3

Hello World,

i was told that it is very easy/simple to push data from a form to 2 tables at the same time. after i did some test, it is not easy… maybe i missed out something.

help Cakephp friends to share some ropes of how i can push a data to 2 tables, which contains different variables…

the codes which i obtained from them are very messy, so not showing yet.

a ctp file from Template, with form helper + 2 Controllers

example : CTP file A, wants to push data to Table A and Table B,

thank you… :bowing_man:

Are the two tables associated, and if so how (hasMany, belongsTo, belongsToMany)? Have you read Converting Request Data into Entities and the related Converting sections following it, and also Creating Inputs for Associated Data?

Hello Zuluru,

ive checked the Model, both tables associated as follows

Table A (Products)

          $this->belongsTo('Users', [
          'foreignKey' => 'user_id',
          'joinType' => 'INNER',
          ]);


        $this->hasMany('ProductImages', [
        'className' => 'ProductImages',
        'foreignKey' => 'product_id',
        //'dependent' => true
        ]);

Table B (Products Images)

        $this->belongsTo('Products', [
        'foreignKey' => 'product_id',
        'joinType' => 'INNER',
         ]);

I am reading your links at the same time to see if there’s something i can learn from therein.

I think something is not right in the Model in terms to their relationship.

i am not able to push 1 form to 2 tables tried several times.

Well, we can guess what it is that you might have done wrong, but it’s far more reliable if you were to post some code here, showing for example how you are creating the fields in your form.

Yes, please find the codes as follows for the add function with images upload feature (the one you helped replied me recently)

                public function add()  {

                

                    $this->loadModel('Categories');

                    $product = $this->Products->newEntity();


                    $this->set(compact('product'));

                    $user = $this->authUser;

                    if ($this->request->is('post')) {

                        $this->loadComponent('Upload');

                        $data = $this->request->getData();
                        $data['user_id'] = $user['id'];
                        $product = $this->Products->patchEntity($product, $data);


                    
                        $this->loadModel('ProductImages');
                        $productImage = $this->ProductImages->newEntity();
                        $productImage = $this->ProductImages
                        ->patchEntity($productImage, $this->request->getData());
         

                        if (!empty($product->getErrors())) {

                            $this->Flash->error(__('Please provide all required information.'));

                            return;
                        }

                        if (!empty($data['image']['name'])) {

                            $ext = Utils::allowedImageExtensions($data['image']['name']);

                            if (!$ext) {

                                $this->Flash->error(__('Provided image is not valid'));

                                return;
                            }



                            if ($this->Products->save($product)) {

                                $id = $product->id;

                                $imagePath =  $this->Products->imagePath;
                                $directory = WWW_ROOT . DS . $imagePath . DS . $id;
                                $dir = new Folder($directory, true, 0755);  //creates target folder if not exists.
                            

                                $resultImg = $this->Upload->upload(
                                    $data['image'],
                                    WWW_ROOT . '/' . $imagePath . '/' . $id . '/',
                                    null,


                                    array('type' => 'resize', 'size' => '1000', 'output' => 'png'),
                                    null
                                );

                            
                            }


                            if (!empty($this->Upload->errors)) {

                                unset($data['image']);

                                $this->Flash->error(__($this->Upload->errors));

                                return;
                            }

                            $data['product_image'] =  $resultImg;
                        
                        }

                        $result = $this->Products->saveData($user, $product, $data);

                        if (!empty($result['errors'])) {

                            $this->Flash->error(__('The post could not be saved. Please, try again.'));

                            $product->setErrors($result['errors']);

                            return;
                        }

                        if ($result) {

                            return $this->redirect(['controller' => 'ProductImages', 'action' => 'index', $product->id]);

                        } else {

                            $this->Flash->error(__('The Product could not be saved. Please, try again.'));
                        }
                    }
                }

the following is the add ctp file element

                <?= $this->Form->create($product, ['id' => 'exampleFullForm', 'type' => 'file']); ?>
                <div class="row row-lg">
                    <div class="col-xl-12 form-horizontal">

                        <div class="form-group row">
                            <label class="col-xl-3 col-md-3 form-control-label">Main Product Image
                                <span class="required">*</span>
                            </label>
                            <div class=" col-xl-8 col-md-9">
                                <?php echo $this->Form->control('image', array(
                                    'label' => false,
                                    'div' => false, 'type' => 'file',
                                    'class' => 'form-control',
                                    'id' => 'input-file-now',
                                    'data-plugin' => 'dropify',
                                    'data-default-file' => '',

                                )); ?>


                                <?php if ($product->product_image != null) {   ?>

                                    <label class="col-xl-3 col-md-3 form-control-label">Current Product Image
                                        <span class="required">*</span>
                                    </label>

                                <?php
                                    $imgPath = $this->Url->build('/', true) . 'file/image/products/' . $product->id . DS . 'large' . DS . $product->product_image;
                                    echo $this->Html->link(
                                        $this->Html->image($imgPath, ['width' => '100', 'height' => '130']),
                                        $imgPath,
                                        ['escape' => false, 'target' => '_blank']
                                    );
                                }


                                ?>



                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-xl-3 col-md-3 form-control-label">Product Name
                                <span class="required">*</span>
                            </label>
                            <div class=" col-xl-8 col-md-9">
                                <?php echo $this->Form->control('name', array('label' => false, 'div' => false, 'type' => 'text', 'class' => 'form-control')); ?>

                            </div>
                        </div>




                    </div>
                    <div class="form-group col-xl-12 text-right padding-top-m">


                        <?php echo $this->Form->button(__('Save'), array('type' => 'submit', 'class' => 'btn btn-primary center-block')); ?>

                        <?php

                        echo $this->Html->link(
                            __('Next'),
                            ['controller' => 'productImages', 'action' => 'index', $product->id],
                            ['class' => 'btn btn-primary center-block']
                        );
                        ?>

                    </div>
                </div>
                <?= $this->Form->end() ?>
                <?php
                $baseCSS = $this->Url->build('/', true);
                ?>

after i clicked save, the image is saved into Products table, but not at Product Images table, they want to push image file to both tables at same time

If you need to save the same data into two tables, that’s something you can’t do with just the form, you will need custom coding in the controller to handle it. That said, I see you saving twice to the Products table, not at all to the ProductImages table. You create and patch $productImage, but then never reference it again.

hello Zuluru,

yeah, i managed to push them to 2 tables, after reading your message, so its a success! sorry for asking another question, for cakephp is there a simple guide on how to do CRUD? reason i ask is i tend to forget php styles and still at the ionic way of writing codes, so a simple push data to SQL i need to think quite a long time…

Database Access & ORM - 4.x has sections on Reading (R), Saving (CU), and Deleting (D), so that covers all the CRUD. You should also make yourself aware of Code Generation with Bake - 2.x, which can be used to generate boilerplate code for you with all the standard methods, ready for you to add custom business logic to.

Dear Zuluru, thank you for the link for refreshing my memory for cakephp, i found out that if there is a console.log function like ionic which we can inspect elements direction from chrome inspect function it would be much easier for me to debug, currently im using the bottom right corner to read the codes or using debug($variable) to read codes.

currently im picking up my pace in writing cakephp codes.