I'm trying to save relations in third table 'Relations'. Here's code:
Controller save action:
$relations = $_POST['VideoCaptions']['countries'];
$model->attachBehavior('ManyToManyRelationBehavior', array(
'class' => 'ManyToManyRelationBehavior',
'modelNameRelation' => 'Relations',
'firstField' => 'video_captions',
'secondField' => 'video_countries',
'relationList' => $relations,
));
ManyToManyRelationBehavior class afterSave action:
if (is_array($this->relationList)){
$model_ = $this->modelNameRelation;
$model_::model()->deleteAll("first_field = :firstField AND first_field_value = :firstFieldValue AND second_field = :secondField", array(
":firstField" => $this->firstField,
":firstFieldValue" => $this->owner->id,
":secondField" => $this->secondField
));
foreach ($this->relationList as $value){
$model_ = new $this->modelNameRelation;
$model_->first_field = $this->firstField;
$model_->first_field_value = $this->owner->id;
$model_->second_field = $this->secondField;
$model_->second_field_value = intval($value);
if (!$model_->save()) return false;
}
}
return true;
var_dump($model_) returns that model exists, but $model->save() doesn't save any data in table 'Relations'. I can't understand why. Can anyone help?
What are the validations you set up for this "modelNameRelation"? You should try the insert() method instead of save() and check whether it will work or not? Save first validates then call insert() or update() method.
SOLVED:
foreach ($this->relationList as $value){
$model = new $this->modelNameRelation;
$model->first_field = $this->firstField;
$model->first_field_value = $this->owner->id;
$model->second_field = $this->secondField;
$model->second_field_value = intval($value);
Yii::app()->db->createCommand()->insert($model->tableName(), $model->attributes);
}
Related
I have this problem in uploading my csv to my database (SQL). I am using Maatwebsite... And here's is my controller:
class UploadCSV extends Controller
{
public function store(Request $request){
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['s_id' => $value->id,
'school_name' => $value->sname,
'region' => $value->reg,
'province' => $value->prov,
'municipality' => $value->mun,
'division' => $value->div,
'district' => $value->dis,
'enrollment_sy_2014_2015' => $value->enrolled,
'mooe_in_php_for_fy_2015' => $value->mooe,
'latitude' => $value->lat,
'longitude' => $value->lng
];
}
Map::insert($arr);
dd('Insert Record successfully.');
//return json_encode($arr);
}
}
dd('Request data does not have any files to import.');
}
Which gives me this endless error message:
The CSV contains only 200+ rows. Any help would be appreciated. Thanks in advance :))
Maybe try something like this, create new Model (assuming Map is the name of your Model and save():
<?php
class UploadCSV extends Controller
{
public function store(Request $request){
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$entry = new Map;
$entry->s_id = $value->id;
$entry->school_name = $value->sname;
$entry->region = $value->reg;
$entry->province = $value->prov;
$entry->municipality = $value->mun;
$entry->division = $value->div;
$entry->district = $value->dis;
$entry->enrollment_sy_2014_2015 = $value->enrolled;
$entry->mooe_in_php_for_fy_2015 = $value->mooe;
$entry->latitude = $value->lat;
$entry->longitude = $value->lng;
$entry->save();
}
}
}
dd('Request data does not have any files to import.');
}
}
I'm beginner in PHP and phalcon, I want to use custom validation and creating default value.
My controller is:
use Phalcon\Mvc\Controller;
class OspoController extends Controller
{
public function indexAction()
{
}
public function createAction()
{
$ospo = new Ospos();
// Store and check for errors
$success = $ospo->save(
$this->request->getPost(),
array('isEmailConfirmed', 'email', 'password', 'salt' ,'phoneNum', 'verifiedPhoneStatus', 'languageId', 'firstName', 'lastName', 'address', 'cityId', 'provId', 'countryId', 'postCode')
);
$data = array();
if ($success) {
$data[] = array(
'status' => 'success'
);
echo json_encode($data);
} else {
foreach ($ospo->getMessages() as $message) {
$msg = $message->getMessage();
$data[] = array(
'message' => $msg
);
}
echo json_encode($data);
}
$this->view->disable();
}
I want if isEmailConfirmed is null - I want to create value that isEmailConfirmed = 0;
How to change array value of getPost()?
(can I do this) Should i change the code with
$isEmailConfirmed = $_POST['isEmailConfirmed'];
and
$ospo->save($isEmailConfirmed, $etc, $etc)?
Thank you.
First of all, you can just store POST data in a variable. Then just check for null and assign default value if needed before saving.
$data = $this->request->getPost();
if (!isset($data['isEmailConfirmed']) {
$data['isEmailConfirmed'] = 0;
}
Another way is to save null value, but in that case you should set up DEFAULT for that column in your database table.
In ZF2, I have a custom form element factory. It creates a custom MultiCheckbox and fills the checkbox values and labels from a db query.
class MyMultiCheckboxFactory
{
public function __invoke(FormElementManager $formElementManager)
{
$multiCheck = new \Zend\Form\Element\MultiCheckbox();
$serviceManager = $formElementManager->getServiceLocator();
$mapper = $serviceManager->get('Path\To\Mapper\To\Query\DB');
$descriptions = $mapper->findDescriptions($id);
// some processing to prepare $value_options array
$multiCheck->setOptions([
'label' => 'blah-blah',
'value_options' => $value_options
]);
return $multiCheck;
}
}
My problem is as follows. The method findDescriptions($id) depends on the $id which I can get from the route. But when I use MyMultiCheckbox in the form like this:
public function init()
{
$this->add([
'type' => 'Path\To\MyMultiCheckbox',
'name' => 'someName'
]);
}
I don't know how to pass the $id into the MyMultiCheckbox.
Could anyone help pleeeeeeeeeease?
You can fetch the id via the 'route match' instance inside the factory.
$event = $serviceManager->get('Application')->getMvcEvent();
$id = $event->getRouteMatch()->getParam('id', false);
if (empty($id)) {
throw new ServiceNotCreatedException('id not set!');
}
$descriptions = $mapper->findDescriptions($id);
i want to test a controller function getStructuredChartData which takes $chartData as a parameter
function getStructuredChartData($chartData = null) {
$structuredChartData = array();
$structuredChartData['Create'] = array();
$structuredChartData['Create']['type'] = 'column';
$structuredChartData['Create']['exportingEnabled'] = TRUE;
if($chartData == null) {
$structuredChartData['null'] = TRUE;
} else {
$structuredChartData['ChartParams'] = array();
$structuredChartData['ChartParams']['renderTo'] = 'columnwrapper';
....
....
....
}
}
and to test this the code i have written in testcase controller is as follows
public function testTrendsReportWithAjaxRequest() {
$chartData = array();
$from_date = new DateTime("2014-07-01");
$to_date = new DateTime("2014-07-31");
$chartData['StartDate'] = $from_date;
$chartData['EndDate'] = $to_date;
$chartData['View'] = "Daily";
$chartData['Data'][(int) 0]['Project']['name'] = 'Test Project #1';
$chartData['Data'][(int) 0][(int) 0] = array('reviewed' => '1', 'modified' => '2014-07-16');
debug($chartData);
// Invoke the index action.
$result = $this->testAction(
'/reports/getStructuredChartData',
array('data' => $chartData)
);
debug($result);
$this->assertNotEmpty($result);
}
now my concern is that how to pass $chartData to controller function in testCase.
Currently in Controller function $chartData occurs as NULL and the if condition
if($chartData == null) {
$structuredChartData['null'] = TRUE;
}
gets executed. moreover i would like else condition
else {
$structuredChartData['ChartParams'] = array();
$structuredChartData['ChartParams']['renderTo'] = 'columnwrapper';
....
....
....
}
to be executed.
From CakePHP testing documentation
By supplying the data key, the request made to the controller will be POST. By default all requests will be POST requests. You can simulate a GET request by setting the method key:
You have to add get as method:
$result = $this->testAction(
'/reports/getStructuredChartData',
array('data' => $chartData, 'method' => 'get')
);
If you have your routes properly configured you can just pass the full url:
$result = $this->testAction(
'/reports/getStructuredChartData/test'
);
Again from CakePHP docs
// routes.php
Router::connect(
'/reports/getStructuredData/:chartData',
array('controller' => 'reports', 'action' => 'getStructuredData'),
array(
'pass' => array('chartData'),
)
);
To pass $chartData as argument in TestCaseController what i did is ::
$this->controller = new ReportsController();
$result = $this->controller->getStructuredChartData($chartData);
I am looking for a way to access and change the DATABASE_CONFIG variables, based on user input. Using CakePHP I created a custom datasource, based on the one provided in the docs, to access an external API. The API returns a JSON string containing the 12 most recent objects. I need to be able to change the page number in the API request to get the next 12 results, as well as accept a free text query entered by the user.
app/Config/Database.php
class DATABASE_CONFIG {
public $behance = array(
'datasource' => 'BehanceDatasource',
'api_key' => '123456789',
'page' => '1',
'text_query' => 'foo'
);
}
app/Model/Datasource/BehanceDataSource.php
App::uses('HttpSocket', 'Network/Http');
class BehanceDatasource extends DataSource {
public $description = 'Beehance datasource';
public $config = array(
'api_key' => '',
'page' => '',
'text_query' => ''
);
public function __construct($config) {
parent::__construct($config);
$this->Http = new HttpSocket();
}
public function listSources($data = null) {
return null;
}
public function describe($model) {
return $this->_schema;
}
public function calculate(Model $model, $func, $params = array()) {
return 'COUNT';
}
public function read(Model $model, $queryData = array(), $recursive = null) {
if ($queryData['fields'] === 'COUNT') {
return array(array(array('count' => 1)));
}
$queryData['conditions']['api_key'] = $this->config['api_key'];
$queryData['conditions']['page'] = $this->config['page'];
$queryData['conditions']['page'] = $this->config['text_query'];
$json = $this->Http->get('http://www.behance.net/v2/projects', $queryData['conditions']);
$res = json_decode($json, true);
if (is_null($res)) {
$error = json_last_error();
throw new CakeException($error);
}
return array($model->alias => $res);
}
}
Is there anyway to access and change the $behance array, or is there another way to go about accessing an external API with cakePHP that I am totally missing?