How do I split my HABTM tags? - has-and-belongs-to-many

I want to take a field in the add form of the Post, explode it at the spaces, and save each word as a Tag, which HasAndBelongsToMany Post. So, for each unrecognized tag, it will create a new one, but if the Tag already exists, it will only create a new reference in the posts_tags tables. I've tried using saveAll, saveAssociated, and few foreach hacks, and I am not exactly sure where it went wrong, but I cannot figure out how to save the associate data. Any sort of outline of how to get the tag data from the form to the database would be appreciated.
//in model
public function parseTags($data) {
$str = $data['Tag'][0]['title'];
$tags = explode('',$str);
for ($i=0; $i<count($tags); $i++) {
$data['Tag'][$i]['title'] = $tags[$i];
}
return $data;
}
//in view
echo $this->Form->input('Tag.0.title',array('label'=>'Tags'));
//in controller
public function add() {
if ($this->request->is('post')) {
$this->Question->create();
$this->request->data['Question']['user_id'] = $this->Auth->user('id');
$this->request->data = $this->Question->parseTags($this->request->data);
if ($this->Question->saveAll($this->request->data)) {
$this->Session->setFlash(__('The question has been saved'), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The question could not be saved. Please, try again.'));
}
}
$users = $this->Question->User->find('list');
$this->set(compact('users'));
}

You must first check if Tag saved before or not, if not saved, You can save it. So before you save your model ,all of your tags is saved before.
something like this:
/* $tag_list is exploded tags*/
foreach ($tag_list as $tag) {
$res = $this->Tag->find('first', array('conditions' => array('Tag.name' => $tag)));
if ($res != array()) {
$tag_info[] = $res['Tag']['id'];
} else {
$this->Tag->create();
$this->Tag->save(array('Tag.name' => $tag));
$tag_info[] = sprintf($this->Tag->getLastInsertID());
}
}
$this->model->data['Tag']['Tag'] = $tag_info;

Related

CodeIgniter 3 code does not add data to database into 2 different tables (user_info & phone_info)

The problem is when I entered a new name no data is added. A similar thing happen when I entered an already existing name. Still, no data is added to the database. I am still new to CodeIgniter and not entirely sure my query builder inside the model is correct or not.
In the Model, I check if the name already exists insert data only into the phone_info table. IF name does not exist I insert data into user_info and phone_info.
Controller:
public function addData()
{
$name = $this->input->post('name');
$contact_num = $this->input->post('contact_num');
if($name == '') {
$result['message'] = "Please enter contact name";
} elseif($contact_num == '') {
$result['message'] = "Please enter contact number";
} else {
$result['message'] = "";
$data = array(
'name' => $name,
'contact_num' => $contact_num
);
$this->m->addData($data);
}
echo json_encode($result);
}
Model:
public function addData($data)
{
if(mysqli_num_rows($data['name']) > 0) {
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info',$phone_info);
} else {
$user_info = array(
'name' => $data['name']
);
$this->db->insert('user_info', $user_info);
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info', $phone_info);
}
}
DB-Table user_info:
DB-Table phone_info:
Extend and change your model to this:
public function findByTitle($name)
{
$this->db->where('name', $name);
return $this->result();
}
public function addData($data)
{
if(count($this->findByTitle($data['name'])) > 0) {
//.. your code
} else {
//.. your code
}
}
Explanation:
This:
if(mysqli_num_rows($data['name']) > 0)
..is not working to find database entries by name. To do this you can use codeigniters built in model functions and benefit from the MVC Pattern features, that CodeIgniter comes with.
I wrapped the actual findByName in a function so you can adapt this to other logic and use it elswehere later on. This function uses the query() method.
Read more about CodeIgniters Model Queries in the documentation.
Sidenote: mysqli_num_rows is used to iterate find results recieved by mysqli_query. This is very basic sql querying and you do not need that in a MVC-Framework like CodeIgniter. If you every appear to need write a manual sql-query, even then you should use CodeIgniters RawQuery methods.

Logic error when add tag for post in Laravel

I trying function add tag for post in laravel. This is update code:
public function update(PostRequest $request, $id)
{
$post = Post::find($id);
$post->update($request->all());
if ($request->tags) {
$tagNames = explode(',', $request->tags);
$tagIds = [];
foreach ($tagNames as $tagName) {
$tagCount = Tag::where('name', '=', $tagName)->count();
if ($tagCount < 1) {
$tag = $post->tags()->create(['name' => $tagName]);
} else {
$post->tags()->detach();
$tag = Tag::where('name', $tagName)->first();
}
$tagIds[] = $tag->id;
}
$post->tags()->sync($tagIds);
}
return back()->with('success', 'Successfully');
}
It works well with pivot table, this has been resolved.
My problem lies in the tag table. When I delete all tags and retype new tag or exist tag, ok it works.
But when I do not change or keeping old tag and continue add new tag will cause an logic error. It will automatically add the record to the tags table.
For example: my post has 3 tags: test1, test2, test3. I keep it and add a tag: test4 then in the table tag automatically add tag: test2, test3, test4.
Is there a solution to my problem? Where was I wrong? I spent almost 2 days for it. I don't want to use package. Vote up for answer useful.
First, use firstOrCreate, it is short and convenient. Then, don't detach, it is useless, sync makes connected tags just like the array tagIds, it removes non-existing elements out of a pivot table and adds new ones.
In addition, you have spaces between commas and words, so you need to trim it.
if ($request->tags) {
$tagNames = explode(',', $request->tags);
$tagIds = [];
foreach ($tagNames as $tagName) {
$tag = Tag::firstOrCreate(['name' => trim($tagName)]);
$tagIds[] = $tag->id;
}
$post->tags()->sync($tagIds);
}
I think I've understood your bug, it is here
if ($tagCount < 1) {
$tag = $post->tags()->create(['name' => $tagName]);
} else {
$post->tags()->detach();
$tag = Tag::where('name', $tagName)->first();
}
It means that when you pass a new tag, it removes all the related tags out of the post. If you pass only old tags, they are not removed.

Get list of all product attributes in magento

I have been doing frontend magento for a while but have only just started building modules. This is something i know how to do frontend but i am struggling with in my module. What i am trying to achieve for now, is populating a multiselect in the admin with all available product attributes. Including custom product attributes across all product attribute sets. I'm not entirely sure what table this will require because i don't want to assume that Flat Category Data is enabled.
I have created my admin area in a new tab in system config, i have created a multiselect field that is currently just being populated with three static options. This much works. Could anyone help me by pointing a finger in the right direction... currently this is what i have so far (for what it's worth).
<?php
class test_test_Model_Source
{
public function toOptionArray()
{
return array(
array('value' => 0, 'label' =>'First item'),
array('value' => 1, 'label' => 'Second item'),
array('value' => 2, 'label' =>'third item'),
);
}
}
///////////////////////////// EDIT /////////////////////////////////////
I feel like i might be onto something here, but it's only returning the first letter of every attribute (so i'm not sure if its even the attributes its returning)
public function toOptionArray()
{
$attributes = Mage::getModel('catalog/product')->getAttributes();
$attributeArray = array();
foreach($attributes as $a){
foreach($a->getSource()->getAllOptions(false) as $option){
$attributeArray[$option['value']] = $option['label'];
}
}
return $attributeArray;
}
///////////////////////////////// EDIT //////////////////////////////////////
I am not extremely close as i now know that the array is returning what i want it to, all attribute_codes. However it is still only outputting the first letter of each... Anyone know why?
public function toOptionArray()
{
$attributes = Mage::getModel('catalog/product')->getAttributes();
$attributeArray = array();
foreach($attributes as $a){
foreach ($a->getEntityType()->getAttributeCodes() as $attributeName) {
$attributeArray[$attributeName] = $attributeName;
}
break;
}
return $attributeArray;
}
I have answered my own question. I have found a way that worked however i'm not sure why, so if someone could comment and explain that would be useful. So although having $attributeArray[$attributeName] = $attributeName; worked when it came to a print_r when you returned the array it was only providing the first letter. However if you do the following, which in my opinion seems to be doing exactly the same thing it works. I can only imagine that when rendering it wasn't expecting a string but something else. Anyway, here is the code:
public function toOptionArray()
{
$attributes = Mage::getModel('catalog/product')->getAttributes();
$attributeArray = array();
foreach($attributes as $a){
foreach ($a->getEntityType()->getAttributeCodes() as $attributeName) {
//$attributeArray[$attributeName] = $attributeName;
$attributeArray[] = array(
'label' => $attributeName,
'value' => $attributeName
);
}
break;
}
return $attributeArray;
}
No need to do additional loops, as Frank Clark suggested. Just use:
public function toOptionArray()
{
$attributes = Mage::getResourceModel('catalog/product_attribute_collection')->addVisibleFilter();
$attributeArray = array();
foreach($attributes as $attribute){
$attributeArray[] = array(
'label' => $attribute->getData('frontend_label'),
'value' => $attribute->getData('attribute_code')
);
}
return $attributeArray;
}
You can try to get attributes in other way, like this
$attributes = Mage::getSingleton('eav/config')
->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getAttributeCollection();
Once you have attributes you can get options in this way (copied from magento code)
$result = array();
foreach($attributes as $attribute){
foreach ($attribute->getProductAttribute()->getSource()->getAllOptions() as $option) {
if($option['value']!='') {
$result[$option['value']] = $option['label'];
}
}
}

codeigniter validate

Hello I have a forum and when a user creates a comment, I want that if he didn't type anything I want to show him an error that he must type something in :) but I dont know how to put him the the thread he is in.
I have this
if($this->_submit_validate_comment() == false) {
$this->post(); return;
}
function _submit_validate_comment() {
$this->form_validation->set_rules('kommentar', 'kommentar', 'required|min_length[4]');
return $this->form_validation->run();
}
You could do this with jquery but if that is not an option you could get the forum or topic id from the url (assuming your are using the url this way).
For example:
http://yoursite.com/forum/topic/12
if($this->_submit_validate_comment() == false)
{
$topic_id = $this->uri->segment(3);
redirect('/forum/topic/'. $topic_id);
}
Or
if($this->_submit_validate_comment() == false)
{
$topic_id = $this->uri->segment(3);
$this->topic($topic_id);
}
Hope this helps.
Thanks for helping i can see what you mean but it just dont work :b,
i have this
$topic_id = $this->uri->segment(3);
$this->post($topic_id);
return;
and my url is
localhost:8888/ci/index.php/forum/create_comment
it looks like it cant find the ID
my URL to the forum is
localhost:8888/ci/index.php/forum/post/33
this is my functions
function create_comment() {
if($this->_submit_validate_comment()
== false) { $id = $this->uri->segment(3);
$this->post($id); return;
//echo "validate fejl, kontakt lige
en admin!"; } else { $data =
array( 'fk_forum_traad' =>
$this->input->post('id'),
'brugernavn' =>
$this->session->userdata('username'),
'indhold' =>
$this->input->post('kommentar'),
'dato' => 'fejl' );
$this->load->model('forum_model');
$this->forum_model->create_comment($data);
redirect('/forum/post/'.
$this->input->post('id').'',
'refresh'); }
}
function post($id) {
$this->load->model('forum_model');
$data['query'] =
$this->forum_model->posts($this->uri->segment(3));
$this->load->model('forum_model');
$data['comments'] =
$this->forum_model->comments($this->uri->segment(3));
$data['content'] = 'forum_post_view';
$this->load->view('includes/template',
$data); }
Why not pass in the return uri in the form submission using a hidden input field? No additional work will be needed by the controller other than validation of the return uri before performing a redirect.
Place the validation error string in session class's flashdata for echoing out in the form, along with any other data used to pre-populate your form)

Form validation with custom callback function

I created a "callback" function to check if the username exists in the DB.
I have multiple rules for the "username" field, but the only thing that work is my callback function. It refuses to check against the other rules. I tried leaving the field empty, and the "required" rule never kicked in.
Controller:
account.php
function register() {
$this->load->library('validation');
$fields['username'] = "trim|required|callback_username_check";
etc ...
etc ...
$this->validation->set_rules($fields);
if ($this->validation->run()) {
$records = array();
$records['username'] = $this->validation->username;
etc ...
etc ...
$data = $this->account_model->registerNewAccount($records);
}
$this->load->view('register_view');
}
function username_check($username) {
$m = new Mongo();
$collection = $m->selectDB( DBNAME )->selectCollection( TABLE );
$data = $collection->count(array("username" => $username) );
if($data == 1) {
$this->validation->set_message('username_check', '%s is already taken!');
return false;
} else {
return true;
}
}
Try using the new form_validation class here:
http://ellislab.com/codeigniter/user_guide/libraries/form_validation.html
I believe there was a bug about it.

Resources