I am parsing cakephp using xml parser. It parses it just fine. Its a huge xml. I now need to enter that into a database. Any easy way to do it without going into too much trouble with all those arrays and sub arrays
Thanks
This all depends on what the array looks like and how you want to store the data. If you just need to capture the array, you can use serialize:
$data = serialize($xml_array)
And store that in a text field.
If you need to store each item in the array, you can do that easy enough as long as there are not sub-arrays within the array. If it is for example and array like this:
array(
[MyArray] => (
[Field1] => 'data',
[field2] => 'data',
)
)
and the Field1 and field2 match the columns of the table, just change [MyArray] to the model name and pass the array to the model->save() function and it will save the data.
However, if you have sub-array information:
array(
[MyArray] => (
[Field1] => array([sub_array] => 'more_data'),
[field2] => 'data',
)
)
Your only option is to parse the data into an array that can be saved and then save it.
Related
I am showing data in CGridView from a dynamic SQL Query using CSqlDataProvider. There are some static and some dynamic column. Now I want to do some special formatting like currency in the dynamic columns. But how do I do that when I don't know the number/name of the columns till the query is executed.
Also i want to be able to sort the dynamic columns and again I have the same problem that I don't have all the column names.
Anyone before who worked with dynamic queries and gridview. Could please point me to the right direction or give some ideas how to do it.
In short I am able to successfully show the data in gridview(also dynamic rows) and sort all the static columns. Just need to sort dynamic rows and format dynamic & static columns
Code for GridView:
$tdata=$dataProvider->getData();
//Calculation to get column names
$grid_columns = array_keys($tdata[0]);
foreach($grid_columns as $i=>$ii)
{
//Applying Formula to get Total Row
$grid_final[$i] = array('name'=>$ii,'class'=>'bootstrap.widgets.TbTotalSumColumn');
}
//Grid View
$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'sortableRows'=>true,
'afterSortableUpdate' => 'js:function(id, position){ console.log("id: "+id+", position:"+position);}',
'dataProvider'=>$dataProvider,
'type'=>'striped bordered',
'template' => "{items}\n{extendedSummary}",
'columns'=> $grid_final,
));
Controller Code:
public function actionIndex()
{
if(isset($_GET['month']))
{
$month=$_GET['month'];
}
else
{
$month= 7;
}
//SQL Query with Dynamic Columns
$sql = "SELECt ABC,X,Y,Z, #Column_Names
FROM some_table
WHERE [month] = :month";
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$command->bindParam(':month',$month,PDO::PARAM_STR);
$dataProvider=new CSqlDataProvider($sql,array('keyField' => 'ABC','params' => array(
':month' => $month,
),'sort' => array(
//Here how do i put column names which i don't know yet for sorting
'attributes' => array(
'ABC','X','Y','Z' )),'pagination'=>false));
$this->render('index',array('dataProvider' => $dataProvider, 'month' => $month));
}
I create dynamic columns in Yii like this:
In some_table model, let's name it SomeTable, I declare a maximum number of column names like this:
public $column1, $column2, $column3, $column4;
I create a function in that model, let's name it 'search()' that builds the dataProvider, like your logic states, but I make sure that #Column_Names looks like something like this:
var_column1 as column1, var_column2 as column2, etc.
in validation(), declare all those columns as safe on 'search'
construct a columns array formed from merging model->attributes and all declared columns with their options and assign it to the view, exactly like you do with $grid_final variable
The only drawback here is that you need to know the maximum number of columns, and of course, the big problem of declaring allot of variables if you have tables with allot of columns.
If you are able to get the columns before the grid is rendered, you can also alter the sorting conditions of the dataprovider.
Something like this:
$tdata=$dataProvider->getData();
//Calculation to get column names
$grid_columns = array_keys($tdata[0]);
$dataProvider->setSort(array('attributes'=> $grid_columns));
Or you can of course prepare you own array of attributes with specific settings, or specific formatting according to any logic you have. The thing is - once you have the columns in $grid_columns you can alter the dataProvider sorting, or the gridColumn setting as you need.
I'd like to insert data into a mysql table using 'the cakephp way'.
I have a multi-stage program that stores data to a session, and toward the end of the program I'd like to write the session data to the database. I could do this using a standard sql insert statement but would like to know how this should be done using cakephp. (Most of the cakephp doc discusses sending data from a webform, and I'd like to manually submit session data.)
Should I manually format the session data in this format and then send this to the model? And if so, is there a helper function for this?
Array
(
[ModelName] => Array
(
[fieldname1] => 'value'
[fieldname2] => 'value'
)
)
Yes, that's the way to do it. There's really no need for a helper function, just use the ones you normally would.
$name = 'Foo';
$city = 'Bar';
$this->ModelName->save(
array(
'name' => $name,
'city' => $city
)
);
I'm sorry, I am a newbie in CakePHP and I am a little bit confused in this subject, let me explain:
I have a relationship between two tables. One of the table is Dose and the other is tank. So, one Tank belongs to a Dose. A Dose has many Tanks. The table schema is:
CREATE TABLE `doses` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`dose` INT(5) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
In my Tank view I have the following code:
<?php echo $form->input('dose_id', array('class'=>'input', 'label' => ''));?>
Each 'dose' (field) from Dose table correspond to a value, such as 200, 300, and so forth. I need to use these numbers to calculate others numbers before to insert into my database (table tank). For instance, my code in tanks_controllers:
$t_u = $this->data['Tank']['tipo_uso_id'];
if( $t_u == '1'){
$this->data['Tank']['producao_adubo_diaria'] = $this->data['Tank']['dose_id'] * 0.10;
.
.
.
However, it is bringing to me the ID of the Dose and not the value (dose field). Where can I set up this to bring me the correct data (dose)? I tried to set up this way in my model:
'Dose' => array(
'className' => 'Dose',
'foreignKey' => 'dose_id',
'conditions' => '',
'fields' => 'dose',
'order' => ''
)
It did not work.
I appreciate your time helping me.
Thanks in advance.
it is bringing to me the ID of the Dose and not the value (dose field). Where can I set up this to bring me the correct data (dose)?
You need to get it from the db (model), not from the view. So you need to do a find(). If you are new to Cake, you should read the cookbook first to see how it works.
What does $form->input('dose_id') produce? A dropdown? If so; by default cake will produce a dropdown with the value containing (dose_)id, and the text you see as the value of $displayField(usually name/title).
To do this; if I understand you, you would need to first query doses for all the values and store the result in an array using the dose value as the key AND the value, rather than the id as you normally would. You would then be able to access the actual dose value from $this->data.
$doseArray=array();
$doses = $this->Dose->find('all');
foreach($doses['Dose'] as $k => $v) {
$doseArray[$v] = $v;
}
perhaps. Seems a bit redundant so I might be off.
i have a problem i can't figure out
in my cake app i have a form that saves multiple data..
one of my input fields is a select field so i have in the view:
echo $form->input('Booking.room_id', array(
'type' => 'select',
'options' => $booking_options
));
where $booking_options is an array that outputs:
Array
(
[23] => Room name1
[24] => Room name2
)
so when i save the form...
the values in the Booking table for room_id are not 23 or 24 but instead they save as 13 and 14
where can be the problem?
Not the answer to your problem, but you should try the Cake way of populating Select boxes properly!
In your controller:
function add() {
$this->set('rooms',$this->Booking->Room->find('list'));
}
In your Form
$this->Form->input('room_id');
This will automatically create a select box with the rooms found in the find('list'), this lowers the chance on errors.
(make sure the 'rooms' table uses the fields 'id' and 'name')
I am trying to 'tag' multiple 'points' with multiple tags. I'm tagging my single points successfully. Unfortunately, when i try and use a tag, such as 'test2' on another point as a tag it is either giving me a duplicate entry error if i have my 'unique' set to false or if 'unique' is set to true, it will del my tag for all other points for 'test2' and create a single new one.
Here is what i have for my post data:
Array
(
[Tag] => Array
(
[id] => 4b7af6d7-787c-4f10-aa49-2502c0a80001
[name] => Test2
)
[Point] => Array
(
[id] => 4b47c66f-a130-4d12-8ccd-60824051e4b0
)
)
In my tag model i have this:
public $hasAndBelongsToMany = array(
'Point' => array(
'className' => 'Point',
'joinTable' => 'points_tags',
'foreignKey' => 'tag_id',
'associationForeignKey' => 'point_id',
'unique' => false)
);
I have tried this with 'unique' set as true, too. Unfortunately, this will delete any other instances of 'Test2' in the join table ('points_tags').
I have tried this using both save() and saveAll(). Both are giving me this error:
Warning (512): SQL Error: 1062: Duplicate entry '4b7af6d7-787c-4f10-aa49-2502c0a80001-4b47c66f-a130-4d12-8ccd-608' for key 'MAN_ADD' [CORE/cake/libs/model/datasources/dbo_source.php, line 527]
Query: INSERT INTO points_tags (tag_id,point_id,id) VALUES ('4b7af6d7-787c-4f10-aa49-2502c0a80001','4b47c66f-a130-4d12-8ccd-60824051e4b0','4b7b39f3-46f8-4744-ac53-3973c0a80001')
Thoughts????
Suggestions????
Where does the id come from? I'm guessing its a primary key of the table, and from what I understand from your post (please write more clearly, help us help you) the problem isn't with points or tags, but with the id in the points_tags table.
When you use the save method, are you doing it inside of a loop? Remember, best practice is to call model::create() whenever you're saving in a loop.
I frequently find that when I have issues with the HABTM saving behavior, it's because I didn't call model::create.