I have the following structure which I need to be inserted in the Target table:
Target table:
target_id, client_crop_id, amount
ClientCrop table:
client_crop_id, client_id, crop_id
Client table:
client_id, client_name
Crop table:
crop_id, crop_name
My question is: At the moment of inserting a new Target, my view has the id of client and of crop, how will CakePHP know that the field client_crop_id at Target Model is the union of thus both quoted above? should I call a method at beforeSave() of Target to fetch the id of ClientCrop?
Thanks.
You can add the desired fields in your view:
<?php
echo $this->Form->hidden('ClientCrop.cient_id', array('value' => $yourVar));
echo $this->Form->hidden('ClientCrop.crop_id', array('value' => $yourVar));
?>
But I do not recommend this approach due security. Try to set it directly in your controller action after post:
<?php
$this->request>data['ClientCrop']['client_id'] = $yourVar;
$this->request>data['ClientCrop']['crop_id'] = $yourVar;
?>
Then you should use the saveAssociated method.
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
Related
I have a form where I am adding some data to db, but I want to avoid duplicate records if user clicks multiple times on the button, I can disable the button using JS but I want to have some checking on server side as well.
Currently on form I am setting a session variable with random number and sending it to controller using textbox (hidden) and then in controller I check if session variable is equal to textbox then add to db - but still the data adds multiple time in db, would appreciate if someone could help. Thanks.
Controller:
if ($request->token == session('test')){
session()->forget('test');
sleep(20); (this i added in order to test)
TableName::create([
'code' => 'test',
'name' => 'testing',
]);
return "done";
} else {
return "stopped";
}
Blade:
{{session(['test'=> rand()])}}
<input type="text" value="{{session('test')}}" name="token">
There are two methods in Laravel firstOrCreate or firstOrNew.
Refer https://laravel.com/docs/5.8/eloquent
The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned
// Retrieve flight by name, or create it with the name, delayed, and arrival_time attributes...
$flight = App\Flight::firstOrCreate(
['name' => 'Flight 10'],
['delayed' => 1, 'arrival_time' => '11:30']
);
You can check with not exist in MYSQL, check Below
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;
In my form, I created the value by populating the dropbox from values from a table.
<?php echo $form->dropDownList($model,'status', CHtml::listData(Statusprospect::model()->findAll(), 'id', 'status'),array('prompt' => 'Select')); ?>
When I view the record it has a 1, as it should for status. How do I make it display the value when the record is viewed, instead of the 1.
The view file code that currently displays the field is this:
<?php echo CHtml::encode($data->status); ?>
The Model does have the relationship defined:
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'status0' => array(self::BELONGS_TO, 'Statusprospect', 'status'),
);
}
How would I accomplish showing the value instead of the number?
Right now this should work $data->status0->status.
Take care that $data->status0->status might not be set if $data->status can be null so make a check beforehand if that is the case. You can use
CHtml::encode(isset($data->status0->status) ? $data->status0->status : '-');
I have a custom joomla MVC component created by http://component-creator.com with 4 tables:
#__mycomponent_items 27 Fields
#__mycomponent_bids 12 Fields
#__mycomponent_journeys 9 Fields
#__mycomponent_users 8 Fields
I am trying to set the relationships between these tables, but in the absence of documentation and experience I am struggling.
The basic relationships between the tables need to allow USERS to make BIDS to deliver ITEMS.
So I have created fields for items like this:
#__mycomponent_items
id
created
updated
ordering
state
checked_out
checked_out_time
created_by
deliverydestination
itemtitle
status
requiredby
listprice
deliveredprice
commission
points_reward
accepted_bid
accepted_bidder
accepted_journey
And for bid like this:
#__mycomponent_bids
id
state
created_by
item_id
buyer
bid
created
updated
bid_status
bid_expires
journey
arrival_date
I am working in templates/mytemplate/html/com_mycomponent/item/default.php and trying to add to that view a list of the current bids on that item. To do that I assume I need to add a custom function to /components/com_mycomponent/models/item.php and the function I have created is follows:
function itemBids() {
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select item record matching the $orderID
$query
//->select('*')
->select($db->quoteName(array('id', 'created_by', 'created', 'bid', 'bid_status', 'arrival_date')))
->from($db->quoteName('#__mycomponent_bids'))
->where('item_id = item.id');
// Reset the query using our newly populated query object.
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$db->setQuery($query);
$itemBids = $db->loadObjectList();
//print_r($itemBids);
}
How do I then access the data in the view /mytemplate/html/com_mycomponent/item/default.php?
I have tried this and it returns nothing:
<ul>
<?php foreach ($itemBids as $itemBid) :?>
<?php $arrivalDate = $itemBid->arrival_date; ?>
<li><strong><?php echo $itemBid->created_by; ?></strong> <small>can deliver for</small> $<?php echo $itemBid->bid;?> <small>
<?php /*?><abbr class="timeago" title="<?php echo $itemBid->created; ?>"></abbr><?php */?>
in <strong><abbr class="timeago" title="<?php echo $arrivalDate; ?>"></abbr></strong></small><div class="uk-badge uk-float-right"><?php echo $itemBid->bid_status; ?></div></li>
<?php endforeach; ?>
</ul>
You wouldn't be putting it in your template like that. the template just holds the layouts that generate the html. Also you need to have a default layout in your views/myview/tmpl folder.
You don't seem to be returning anything from your itemBids() function. You would want to add return $itemBids; or possibly return $this->itemBids; depending on what you are doing elsewhere.
YOu want to get $this->itemBids in your view.html.php class so that it is then available to your layout. THen instead of referring to $itemBids you can refer to $this->itemBids in your loop in the layout.
Have you been through the Creating an MVC Cmponent tutorial? It would probably help you get a sense of how MVC works in Joomla.
OK , as far as I understand you have a method in yourmodel.php and you are trying to access it from the view I did notice that you are not returning any values in your method
return $db->loadObjectList();
let me just make it simple by the below code
//com_component/models/yourmodel.php
class componentModelYourmodel extends JModelLegacy
{
function yourMethod()
{
//code
return $value;
}
}
And then in view file
//com_component/views/yourview/tmpl/default.php
//get the model first
$model=$this->getModel();
//call the method
$items=$model->yourMethod();
//print
print_r($items);
I have built a CakePHP app that allows a user to create posts and add tags (topics) to them. The structure of the database and associations can be seen here: Setting up contains for a join table in CakePHP
I have managed to successfully pull the data out using Contain via the join table. But now I'm trying to build the part where a user enters a topic and then save it BOTH in the Topic Table and the Topic_post table.
I have the following code my add new post method:
if ($this->request->is('post'))
{
//$this->Post->create();
if ($this->Post->save($this->request->data))
{
// Save extra data
$this->Post->saveField('user_id', $this->Auth->user('id'));
$this->Post->saveField('datetime', date('Y-m-d H:i:s'));
$this->Post->saveField('modified', date('Y-m-d H:i:s'));
$this->Post->saveField('status', 1);
// Build slug
$post_title = Sanitize::html($this->request->data['Post']['title'], array('remove'=>true, 'quotes' => ENT_NOQUOTES));
$post_title = String::truncate($post_title, 50, array('exact'=>false,'html'=>false,'ending'=>''));
$this->Post->saveField('slug', Inflector::slug($post_title));
// Redirect the user to the newly created post (pass the slug for performance)
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($this->Post->id),'slug'=>$this->Post->slug));
}
else
{
$this->Session->setFlash('Server broke!');
}
}
So what I need to do now is save the related Topic data which is typed in here in the view:
<?php echo $this->Form->create(); ?>
<?php echo $this->Form->input('Post.title'); ?>
<?php echo $this->Form->input('Post.content', array('type'=>'textarea','label'=>false)); ?>
<?php echo $this->Form->input('Topic.title', array('type'=>'textarea','label'=>'Topics')); ?>
<button type="submit" class="orangeButton small">Create</button>
<?php echo $this->Form->end(); ?>
I have looked at the CakePHP docs and it seems something like saveAll is what I need? But I'm confused as I'm not 100% sure how to use it also it's important to note that a user can save more than one topic to the database and the topics themselves are all unique so for example you can't create a topic that already exists it would instead just use the existing id for the linker.
Can anyone help? As I feel this is rather complex...
You could do something like:
$this->Post->saveAll($this->data, array('validate'=>'first'));
The use of array('validate'=>'first'); ensures that both of our models are validated before saving. Did you mean something like that.
Hope it helps
Sorry for the novice question!
I have a table called cities in which I have fields called id, name, xpos, ypos. I'm trying to use the data from each row to set a div's position and name.
What I'm wondering is what's the best practice for dynamically querying an unknown amount of rows (I don't know how many cities there might be, I want to pull the information from all of them) and then passing the variables from the model into the view and then setting attributes with it?
Right now I've 'hacked' a solution where I run a different function each time which pulls a value using a query ('SELECT id FROM cities;'), then I store that in a global array variable and pass it into view. I do this for each var so I have arrays called: city_idVar, city_nameVar, city_xposVar, city_yposVar then I know that the city_nameVar[0] matches up with city_xposVar[0] etc. Is there a better way?
I'm not sure what you mean by "set a div's position", but here is an attemp:
controller
$data = array(
'cities' => $this->cities_model->get_cities_info()
);
$this->load->view('view',$data);
model
function get_cities_info()
{
return $this->db->query('SELECT id, name, xpos, ypos FROM cities')->result();
}
view
<?php foreach($cities as $city) : ?>
<div style="position:absolute;top:<?= $city->ypos ?>;left:<?= $city->xpos ?>">
<?= $city->name ?>
</div>
<?php endforearch ?>