cakephp,e-commerce,has-and-belongs-to-many , how insert data directly and only into HABTM table ,


how insert data directly and only into HABTM table ,

Question:

Tag: cakephp,e-commerce,has-and-belongs-to-many

I have 1 Category table and second Features table and have association among them is HABTM in cakephp

Now i don't know exactly how to insert values in categories_features table. I used HABTM before but at that time i insert values in this table when one item is created by using "saveAll()" method. but in this case i have seprate page when categories in drop down menu and features in checkbox form.

i tried to create new model categoriesFeature to solve this problem, but when i submit data , data in in this form

Array
(
    [CategoriesFeature] => Array
        (
            [Category_id] => 2
            [feature_id] => Array
                (
                    [0] => 1
                    [1] => 2
                )

        )

)

so i get error

"Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1009]"  
Column not found: 1054 Unknown column 'Array' in 'field list'
"INSERT INTO `ecomerce`.`categories_features` (`feature_id`) VALUES (Array)"

if i'm using wrong approach kindly guide me.

View code to add data in categories_features table

 <?php echo $this->Form->create('CategoriesFeature', array('id' => 'cf'));?>
    <fieldset>
    <legend>Feature Add Form</legend>
    <?php
        echo $this->Form->input('Category_id',array(
                'data-rel' => 'chosen',
                'placeholder' => 'Select Category'
        ));

        $keys= array();
        $values =array();


 echo "<h2> Select Features for above selected Category </h2>";
echo $this->Form->input('feature_id',
        array('label'=>'',
        'type'=>'select',
        'multiple'=>'checkbox',
        'options'=>$features)
        );


        echo $this->Form->submit();
    ?>   
    </fieldset>

table structure

id | category_id | feature_id


Answer:

If you are using the saveAll method, you will need to adjust your array:

Array
(
    [CategoriesFeature] => Array
        0 => array(
            [Category_id] => 2
            [feature_id] => 1

        ),
        1 => array(
            [Category_id] => 2
            [feature_id] => 2

        )
)

You should be using saveMany: as per Model::saveMany(array $data = null, array $options = array())

$data = array(
    array('Article' => array('title' => 'title 1')),
    array('Article' => array('title' => 'title 2')),
);

Related:


cakephp 3 bootstrap-ui change prev/next text


cakephp,cakephp-3.0,cakephp-bootstrap-ui
I have FriendsofCake Bootstrap-ui plugin. I see in the source that it accepts text for the pagination prev and next labels. I am not sure how to exactly set the config option though. PaginatorHelper.php if (isset($options['next'])) { if ($options['next'] === true) { $options['next'] = $this->config('labels.next'); } $options['after'] = $this->next($options['next'], ['escape'...

Remove resource wrapper from CakePHP REST API JSON


rest,cakephp,cakephp-2.2
My question is similar to this one. I understand the answer given there. The OP of that question doesn't seem to have my issue. I am using CakePHP 2.2.3. I am fetching a resource like this: http://cakephpsite/lead_posts.json and it returns results like this: [ { "LeadPost": { "id": "1", "fieldA":...

CakePHP find WHERE NOT EQUAL


php,cakephp,frameworks
can you see the error guys ? my AND conditions is ignored! I'm getting so frustrated with those arrays.. $transaction_query = $this->Transaction->find('all', [ 'limit' => $countList, 'fields' => ['Transaction.client_id','Transaction.name','Transaction.created','Transaction.message_id','Transaction.credit'], 'conditions' => ['Transaction.id' => $client_id], 'AND' => ['Transaction.name !=' => 'Facturation'] ]); ...

Radio Button CakePHP 3.0


php,cakephp,cakephp-3.0
In CakePHP 2.0 I can actually add 'before', 'after' and 'separator' attributes to the radio button. The attributes will create a div element between my radio options. It seems like these options have been removed from CakePHP 3.0. How can I do that in CakePHP 3.0? <div class="col-xs-6 col-sm-6 col-md-6...

Moving a CakePHP 1.3.2 Application to a New Server


php,cakephp,cakephp-1.3
I have a very old CakePHP 1.3.2 application that used to work on a server under a given domain. I have the original files and now I'm trying to set it up and get it running on a new server under a different domain. At first I had to fix...

CakePHP Unable to insert to database (datetime format)


database,datetime,cakephp,insert
I was new to Cakephp and I actually following the tutorial of the Blog tutorial however I didn't follow their database and try my own. Currently my database: My Model: class FypCakephp extends AppModel { //Table Name public $useTable = 'Report'; public $primaryKey = 'report_id';} My Controller: public function add()...

CakePHP 3 Multiple BelongsTo Associations


php,cakephp,cakephp-3.0
I am using cakePHP version 3.x. When i query the MessagesTable i want to get the Users data for the the sender and the receiver of the message. I have done this many times in cakePHP 2 but i cant figure out why it isn't working in version 3.x. i...

CakePHP - all pages blank except the home page


php,cakephp,cakephp-1.3
I inherited a very old CakePHP application (version 1.3.2) that I have to run on a new server (old server is long gone, I only have the code). I managed to get it going after some configuration and right now the home page loads here: http://m.gratuito24.com/ So far so good,...

Updating fields of model using forms and views on Django 1.7


python,mysql,django,forms,e-commerce
In models.py my Product model is class Product(models.Model): productName = models.CharField(max_length=20, default='1',blank=False,null=False, primary_key = True) userPhone = models.CharField(max_length=20, default='1') userid = models.ForeignKey(Account, default='1',null=True) productDesc = models.TextField(blank=False,null=False, default='1') productCategory = models.ForeignKey(Category, null=False, default='1') productPrice = models.DecimalField(default='0',blank=False,null=False, max_digits=6, decimal_places=2) picture =...

Cakephp MySql Query with WHERE


mysql,cakephp
I have work function: public function index() { $this->set('tables', $this->Table->find('all')); } But how show only column WHERE owner = logged user?...

conditions OR in join cakephp


php,mysql,cakephp
I am a novice in cake and I'm having trouble with a query I want to do in a tables. $options['joins'] = array( array('table'=>'users_views', 'alias' => 'UserView', 'type' => 'inner', 'conditions' => array( 'View.id = UserView.view_id', 'UserView.user_id' => $user_id, 'UserView.like' => 1 ), ) ); $options['order'] = array('View.created' => 'desc');...

cakephp 3 and view cells with use of Cookie


cakephp,cakephp-3.0
I can't find any info about using $this->Cookie in view cells. When i wrote code like this, error will arise: namespace App\View\Cell; use Cake\View\Cell; class CityCell extends Cell { public function display() { $this->Cookie->config('encryption', false); $cookie = $this->Cookie->read('city'); } } and the error is: Error: Call to a member function...

CakePHP 1.3 - Extract URL GET parameters


php,url,cakephp,get,cakephp-1.3
I have CakePHP 1.3.2 application working with similar URLs: /controller/action/name1:value1/name2:value2.html I'm trying to extract the values after the : sign specified by the names before that. I can see the whole URL with no problem using $this->params['url'], however, I can't get the value itself using neither $this->params['name1'], nor $this->params['url']['name1']. Any...

CakePHP 3: change order in dateWidget


cakephp,cakephp-3.0
I found on the CakePHP developer's guide the following hint on how to adjust the order of the fields when using the date form input. It says To control the order of inputs, and any elements/content between the inputs you can override the dateWidget template. However, I cannot find anywhere...

File not Uploading using Ajax in cakephp


php,jquery,ajax,file,cakephp
Am trying to upload an image using Ajax to server. I know the code to upload file using Cakephp, but first i just want to make sure that data/file is uploaded to server for sure by printing the formdata. But it seems that only the data i typed in the...

Cakephp 3 and Postgre add.cpt doesnt work id_parent


postgresql,cakephp,cakephp-3.0
I'm trying to create an easy page on cakephp 3 using postgreSQL. I do not understand where is the problem: I create a table "menus". When I add a new instance (add.cpt) the parent field is empty so I cant add a parent. It's all generated from command "cake bake...

CakePHP 2.x Sending user messages to element('menu')


cakephp,menu,message
I would like to know the best way to send data to an element which appear everytime the page is loaded. For instance, once a user is logged in, I have to recover some informations about him. The User.id, User.name, etc. are recovered using the SessionHelper as follow : <?php...

Best rules to get data with Contain


cakephp,cakephp-3.0
In CakePHP 3 ORM has changed and I can't find the proper way to select needed data from the database. In CakePHP 2, I use contain('User.name','User.id'), but In CakePHP 3 this code doesn't work. So how can I select only id and name from User? The code: $query = $data->find()->contain(['Users'])->execute()->fetchAll('assoc');...

make SQL function SUBSTRING_INDEX work in cakePHP query builder


cakephp,cakephp-3.0
I have a fullname column for authors and would like to extract the surname into another column. I do that with the following raw SQL: SELECT name, SUBSTRING_INDEX(`name`, ' ', -1) AS `surname` FROM qr.authors; Output: Under "Using SQL Functions" the Cookbook says: In addition to the above functions, the...

Changing the order items are retrieved from the DB in CakePHP?


php,cakephp
I've made a forum using CakePHP while following a tutorial and would like to expand it. Currently, in a post it allows me to comment, but they are displayed as newest -> oldest, so it doesn't make as much sense and I would like to reverse this. This is the...

How to Edit User CakePHP 3


cakephp,cakephp-3.0
So I've been trying to get an edit user functionality working in my app, and I'm a little confused as to how to go about doing this with CakePHP 3. This is what I've got for my edit action in my UsersController.php: public function edit() { $this->layout = 'dashboard'; $user...

Cakephp Version 2.x Unable to Show selected file name in edit view


php,cakephp,file-io,editview
Hopefully this is a simple issue. I have a Cakephp MVC set to upload an image and store it in a database table. Index, View and Add are working as I want. However, in the Edit view how can I indicate that the record currently has an uploaded image that...

CakePHP on Shared Windows Plesk Server


cakephp,plesk
I am wondering if it is possible to get CakePHP working on a shared Windows Plesk server? I have extracted the CakePHP files to the /httpdocs/ folder, and have created a web.config file as per the instructions in the CakePHP docs, however all I seem to get is an 'Internal...

Basic CakePHP: Edit Post Method become Add Post Method


cakephp,methods,sql-update,edit
Currently following the blog tutorial however my database and their variable are different. I was looking through the "Edit Post" method and follow the step they given however they turn into "Add Post" method. What is the reason that cause it ? (I have set the hidden field at view...

Cakephp link to view a page in sub folder


cakephp,cakephp-2.0,cakephp-2.3
I wish to display a normal page in a sub-dir of the Pages folder, however cakephp keeps removing the "/" forwardslash and replacing it with "%2F".Ive tried to add the escape=>false flag but it doesnt seem to work. What am i doing wrong? my code; echo $this->Html->link('Tiny MCE plugin',array( 'controller'=>'pages',...

issue Login cakephp


cakephp,login
i'm new cakephp and i have 1 question, please help me! I have 1 table name quan_tri_viens same users, but i don't use table users i read and follow the instructions http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html but i can not sign in Model: QuanTriViensController <?php App::uses('AppController', 'Controller'); class QuanTriViensController extends AppController { public function...

Cakephp 3 - MissingDatasourceConfigException when running phpunit test


php,unit-testing,cakephp,phpunit,cakephp-3.0
I am trying to run some unit tests in CakePHP 3 with PHPUnit 4.7.3, but I`m getting the following error: PHPUnit 4.7.3 by Sebastian Bergmann and contributors. There was 1 error: 1) App\Test\TestCase\Model\Table\MoviesTableTest::testFindMoviesByGenre Cake\Datasource\Exception\MissingDatasourceConfigException: The datasource configuration "default" was not found. C:\xampp\htdocs\movie-pal\vendor\cakephp\cakephp\src\Datasource\ConnectionManager.php:188 C:\xampp\htdocs\movie-pal\vendor\cakephp\cakephp\src\ORM\TableRegistry.php:191...

Mailchimp Ecommerce360 Javascript Implementation


javascript,rest,e-commerce,mailchimp
Wondering if anyone can provide an example of how to pass a request to the /ecomm/order-add function of the Mailchimp API using javascript. This is critical for making use of Mailchimp's Ecommerce360 tracking. Here is documentation from Mailchimps API: https://apidocs.mailchimp.com/api/2.0/ecomm/order-add.php...

Disable password hashing for particular users


php,cakephp,cakephp-3.0
We are using a single table for both admin and normal users. We need to save the admin password in hash format, but save the user password in plain text. How do do that with CakePHP 3.0 EDITED: User's username and password are used as a login credentials on another...

how to display a message if database table is empty in cakephp


cakephp,cakephp-2.3
i can retrieve database entries with $this->set('view_applications', $this->Application->find('all')); but i do not know how to display a message if the results of the above function is empty. here is my controller code public function index() { $this->set('results', $this->Application->find('all')); } and here is my index.ctp view code <h1>Requests for Graduation Registration</h1>...

PHP Multiple cURL requests to REST API stalls


php,rest,cakephp,curl
Currently I have a system that sends multiple requests to a REST API. It is structured something like this: foreach ($data as $d) { $ch = curl_init( $url ); curl_setopt( $ch, CURLOPT_POST, 1); curl_setopt( $ch, CURLOPT_HTTPHEADER, (array of data here)); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec( $ch ); $retry...

Dx trouble writing output: already prepared… - Error in console


java,android,eclipse,e-commerce,braintree
braintree-api-1.6.1-full.jar android:minSdkVersion="14" android:targetSdkVersion="18" I need to implement braintree inside my android app which has no issues, but as I copy the braintree jar file, into my projects libs folder and import the necessary classes, my app crashes. Full error message in console: Dx trouble writing output: already prepared [2015-06-18...

Modify $this->request->data in model CakePHP?


php,cakephp,cakephp-2.6
How can I modify $this->request->data from model in CakePHP. I tried it with code in model User : public function beforeValidate($options = array()) { unset($this->request->data['User']['birthday']); } But it return errors : Notice (8): Indirect modification of overloaded property User::$request has no effect Warning (2): Attempt to modify property of non-object...

Basic CakePHP: Unable to get the id (Edit Method)


cakephp,sql-update
This my database: http://gyazo.com/c6a86127d6f91aae947cf45ee535cecd Example: http://gyazo.com/c23fec3fabb7e4504c42453980fbc372 When I press the edit button , they able to retrieve the data however the page show me empty field instead of the field that have old data. Secondly, unable to undate because they keep send empty id_field back to controller. p.s. add,edit,delete method...

Trouble linking models together in CakePHP2


php,cakephp,cakephp-2.6
I'm using CakePHP 2.6.7. Here is my database (simplified) : ***Users*** id username ***Cars*** id CarMake CarModel NumberPlate user_id ***Addresses*** id address postalcode city country ***Addresses_Users*** user_id address_id This is what I want : One user can have multiple cars and one car is owned by only one user. One...

Access normal php file in cake php


php,.htaccess,cakephp
if i use normal php file so display error of controller missing and my normal php file is in order/api.php in base directory so please help me how can i access this path without error my htaccess code is <IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1...

how to add normal script code to view.ctp in CakePHP 2.2.4


jquery,cakephp
enter code hereI want to insert this code to my .ctp file <script> $(document).ready(function(){ $('open').click(function(){ $('#pop_background').fadeIn(); $('#pop_box').fadeIn(); return false; }); }); </script> it should work with this <a href="#" id="open">Open popup box</a> I have created the relevant CSS files and div for 'pop_background' and 'pop_box'. Now it should be appeared...

Cakephp 3.x Ajax deleting data gives this Error: Unknown method “isNew”


php,ajax,cakephp,cakephp-3.0
I try to delete a record with Ajax in CakePhp 3.0.6. Here is the jquery in my View (start.ctp) <script> $('.delavailable').click(function(){ var dataString = 'ID=' + $(this).attr('id'); $.ajax({ type: 'POST', url: '/ID/admins/delavailable.json', data: dataString, beforeSend: function(xhr) { xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); } }); }); Controller (AdminsController.php) public function delavailable() { $this->loadModel('TeamFree'); if($this->request->is('ajax'))...

403 Error when trying to remove products from Cart


php,server,e-commerce,opencart,cpanel
I am using a cPanel host and running PHP 5.5. Opencart version 1.5.1. When I try to remove a product from the cart I am getting a 403 forbidden error. This only seems to happen with products that have a lot of options and include text input options. I have...

Checking for 'isUniqueUsername' in cakephp doesn't seem to work?


php,cakephp,registration
I have a register form where when a user registers it asks for their Username, Password and email. For the username, I have a few rules such as: Must be 5-12 characters Must be unique Must use only alpha, numbers, and dashes With that being said, I can't seem to...

Change language in CakePHP


php,cakephp
I am trying to implement language changing buttons in my CakePHP app. I followed the cookbook (http://book.cakephp.org/2.0/en/core-libraries/internationalization-and-localization.html) and now I am able to change language after the user is logged in. My language buttons are linked to actions in my own LanguagesController that looks like this: public function sk() {...

cakephp 3 order by query generates 14 queries with associate tables instead of 1


cakephp,cakephp-3.0
My cakephp3 app works very well and now I wish to order some of the queries by the associated table fields. The query works fine when ordered by a field in the current model. But if I choose to order by a field Models.field in an associated table I now...

Set data from database to generated popup window in CakePHP


cakephp
I have created a popup window in cakephp. <div id="pop_box"> <span id="close">&times;</span> <h2>This is the Popup Box</h2> <span id="selected_content"></span> </div> Now I want to set data to this popup window by getting data from database(MySql). Normally we are getting data from database for a new page using functions in controller....

How to change the message in buildRules [CakePHP 3]?


validation,cakephp,cakephp-3.0
The function below is for being sure the e-mail from form is unique, if it's already in use a message is showed. I want to change this message. public function buildRules(RulesChecker $rules) { $rules->add($rules->isUnique(['username'])); $rules->add($rules->isUnique(['email'])); return $rules; } I tried this way: public function buildRules(RulesChecker $rules) { $rules->add($rules->isUnique(['username'])); $rules->add($rules->isUnique(['email']), ['errorField'...

Is it a good practise store the checkout steps fields in php $_SESSION?


php,session,e-commerce,checkout
I have my e-commerce site with three checkout steps, each button to continue is a POST action and redirect to the next step: if the user navigates by the checkout steps (click on the previous button for example), the form fields don´t show the data posted previously. This form fields...

How can we validate multiple fields with one validation in cakePHP 2.0?


php,cakephp
how can we check firstname and last name is unique validation in cakePHP ? record1: first name :raj last name: kumar if we enter same name in input field , it should show validation message "Record alredy Exists". i know how to validate single field validation. how to validate that...

Cakephp Find all WHERE in two categories


php,cakephp,find,cakephp-2.3
I have trouble finding items that belong to two or more categories in cakephp 2. In my Controller I have the following: $kategories = array(1,2); $options['conditions'] = array('Categorie.id' => $kategories); $items = $this->Item->find('all',$options); The query above shows all Items that have either associated category-id 1 or 2. How can I...

CakePHP2 how to check referral URL only when POST


cakephp
I'm using CakePHP2 (2.6.3) and I need to check referral URL when POST action for avoiding some security issues. In CakePHP 1.x days, there used to be configuration Security.level which can be set to check if referral URL is sort of the same domain, but it seems have been removed....

HABTM CakePHP no results for related model


cakephp,cakephp-2.0,has-and-belongs-to-many
I have problem with HABTM models. When I try to fetch any related model f.e. like this: $this->Tagi->find('first'); I dont get any results for associated model. Result looks like this: array( 'Tagi' => array( 'id' => '1', 'nazwa' => 'sth' ), 'Instytucje' => array() ) I am sure that there...

cakephp use record values in afterDelete


cakephp,cakephp-3.0
I am using the soft delete plugin for my EmployeesTable.php in CakePHP 3.0. When I soft delete an employee I wish to update their associated user table with $user->set('active', false); within the afterDelete() My problem is getting the user_id used in the employees table into the afterDelete() I have even...