2016-04-01 34 views
0

我在我的應用程序中有一個表單。我有幾個fields.I有一個第三方API,它將數據插入到數據庫中。通過使用這個API,我必須插入表單數據。當用戶點擊保存按鈕時,它應該調用API來存儲數據。需要在cakephp上發佈第三方API的表單數據

任何人都可以幫助我。如何在cakephp中實現這一點。

我將不勝感激快速響應

回答

0
  1. 首先在像add.ctp
  2. 您的視圖文件創建表單創建像
 

    function add(){ 
     if(!empty($this->data)){ 
    // Here you perform your API data save 
    } 
    } 

0

的問題是,在你的控制器的功能:在表單中提交之後,是否要處理輸入的數據?

NO的情況:

更改表單的作用到外部API,讓API處理請求。

// add.ctp 
<?php 
echo $this->Form->create("MyModel", [ 
    "type" => "POST", 
    "url" => "link://to.external.api/" 
]); 
echo $this->Form->input(); // all fields 
echo $this->Form->end("Submit"); 
?> 

案例是:

// add.ctp (Just the regular form) 
<?php 
echo $this->Form->create("MyModel"); 
echo $this->Form->input(); // all fields 
echo $this->Form->end("Submit"); 
?> 

然後做任何你想要在你的控制器或模型中的數據,然後使用捲曲把數據上傳到外部API:

PostsController.php 

<?php 
public function Add(){ 
    // Manipulate the form data here before saving it (for example, has a password): 
    $this->request->data["MyModel"]["password"] = sha1($this->request->data["MyModel"]["password"]); 

    // And do a cURL request to post the data to the external API 
    $ch = curl_init("link://to.external.api/"); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($this->request->data["MyModel"])); 

    $response = curl_exec($ch); 
    curl_close($ch); 

    // You can do something with the response of the API here 
    debug($response); 
} 
?> 
+0

我想將REST API作爲單獨的數據源。當我們在mysql的database.php中創建一個數據源。同樣,我需要爲REST API創建數據源。有沒有辦法做到這一點。任何示例實現這種東西: http://book.cakephp.org/2.0/en/models/datasources.html –

+0

你可以,但你將不得不編寫自己的'save()'和'find ()'方法。鏈接背後的示例是否不符合您的需求? – Koen