Новости Joomla

0 Пользователей и 1 Гость просматривают эту тему.
  • 30 Ответов
  • 4468 Просмотров
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Всем привет! Делаю компонент для Joomla 3, подскажите, как сделать множественный выбор из др таблицы? Есть 2 таблицы компоненты, например, продукт и город, т.к. продукт может продаваться не тольков 1 города, а в 2 или 3 и т.д., пытаюсь сделать множественный выбор, поставил в файле product.xml (administrator\components\com_compo\models\forms) multiple="true" и пробовал multiple="1", в админке выбрать можно, но не сохраняет, сбрасывается поле. Подскажите, как сделать?
*

Aleks.Denezh

  • Живу я здесь
  • 3401
  • 428 / 4
Re: Множественный выбор в компоненте
« Ответ #1 : 13.01.2015, 14:02:34 »
Ну выводит только поле, но нет обработки у вас сохранения и обработки получения данных!
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #2 : 13.01.2015, 19:14:52 »
а как сделать? можно хотя бы пример
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Re: Множественный выбор в компоненте
« Ответ #3 : 13.01.2015, 19:51:31 »
Вы в модели как-то сохраняете значение поля, правильно? Только теперь оно не одно, а массив.
Не будь паразитом, сделай что-нибудь самостоятельно!
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #4 : 13.01.2015, 20:24:09 »
нашел вот это http://blog.calebnance.com/joomla-3.0/saving-a-multi-select-field-in-a-custom-joomla-3.x-component.html, по данному примеру получилось, а вот по множественному выбору для города из др таблице по аналогии не получилось((((
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #5 : 13.01.2015, 20:36:00 »
administrator/components/com_comp/models/forms/product.xml

Код
<field
id="city"
name="city"
multiple="1"
required="false"
type="comfilmsCities"
label="COM_COMFILMS_FIELD_CITY_LABEL"
description="COM_COMFILMS_FIELD_CITY_DESC"
size="40"/>

administrator/components/com_comp/controller/product.php

Код
protected function postSaveHook(JModelLegacy &$model, $validData = array()){
// (множественный выбор) установленного формата
if(isset($validData['taguss'])){
$data['taguss'] = implode(',', $validData['taguss']);
}
if(isset($validData['city'])){
$data['city'] = implode(',', $validData['city']);
}
$model->save($data);
}

administrator/components/com_comp/models/product.php

Код
protected function loadFormData(){
// Check the session for previously entered form data.
$app  = JFactory::getApplication();
$data = $app->getUserState('comfilms.edit.film.data', array());

if(empty($data)){
$data = $this->getItem();

// Prime some default values.
if($this->getState('film.id') == 0){
$data->set('catid', $app->input->getInt('catid', $app->getUserState('com_comfilms.films.filter.category_id')));
}

// taguss
if($data->taguss){
$data->taguss = explode(',', $data->taguss);
}

// city
if($data->city){
$data->city = explode(',', $data->city);
}
}

return $data;
}
*

Aleks.Denezh

  • Живу я здесь
  • 3401
  • 428 / 4
Re: Множественный выбор в компоненте
« Ответ #6 : 13.01.2015, 20:42:40 »
Смотрите
1. что вам нужно сделать, это перед сохранением данных массив перевести в json строку
2. Перед выводом данных json строку перевести в массив!

первый пункт делается либо в модели в методе save() либо в табличке в методе bind()
если в модели то делается приблизительно так:
Код: php
public function save( $data ){
$data['city'] = json_encode( $data['city'] );
parent::save( $data );
}
(если метода save нету то добавить, если есть то дополнить только первую строку)

второй пункт в модели делать у вас должен быть метод getItem

Код: php
public function getItem( $id = null ){
if ( $item = parent::getItem( $id ) ) {
$item->city = trim( $item->city) === '' ? array() : json_decode( trim( $item->city) );
}
return $item;
}
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #7 : 13.01.2015, 22:20:15 »
Ошибка
Сохранить не удалось из-за ошибки:


Вставил в administrator/components/com_comp/models/product.php
Код
	protected function loadFormData(){
// Check the session for previously entered form data.
$app  = JFactory::getApplication();
$data = $app->getUserState('comfilms.edit.film.data', array());

if(empty($data)){
$data = $this->getItem();

// Prime some default values.
if($this->getState('film.id') == 0){
$data->set('catid', $app->input->getInt('catid', $app->getUserState('com_comfilms.films.filter.category_id')));
}

// bands
if($data->taguss){
$data->taguss = explode(',', $data->taguss);
}

// city
if($data->city){
$data->city = explode(',', $data->city);
}
}

return $data;
}

public function save( $data ){
$data['city'] = json_encode( $data['city'] );
parent::save( $data );

}

в components/com_comp/models/product.php
Код
	/**
     * Load an JSON string into the registry into the given namespace [or default if a namespace is not given]
     *
     * @param    string    JSON formatted string to load into the registry
     * @return    boolean True on success
     * @since    1.5
     * @deprecated 1.6 - Oct 25, 2010
     */
    public function loadJSON($data){
        return $this->loadString($data, 'JSON');
    }

/**
* Method to get Film data.
*
* @param integer The id of the films.
*
* @return mixed item data object on success, false on failure.
*/
public function getItem($id = null){
if (!isset($this->item)){
$id = $id?$id:$this->getState('films.id');
//Get a table instance.
$table = JTable::getInstance('Film', 'ComfilmsTable');

//Attempt to load the row.
if($table->load($id)){
// Convert the JTable to a clean JObject.
$dataArray = $table->getProperties(1);
$this->item = JArrayHelper::toObject($dataArray, 'JObject');
}elseif($error = $table->getError()){
$this->setError($error);
return false;
}
}
return $this->item;

if ( $item = parent::getItem( $id ) ) {
$item->city = trim( $item->city) === '' ? array() : json_decode( trim( $item->city) );
}
return $item;
}
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #8 : 13.01.2015, 23:12:50 »
HELP)))
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Re: Множественный выбор в компоненте
« Ответ #9 : 13.01.2015, 23:41:52 »
Ошибка
Сохранить не удалось из-за ошибки:
Какая ошибка?
Вставил в administrator/components/com_comp/models/product.php
Код
$data = $this->getItem();
а в данной модели есть модифицированный метод getItem()?
Не будь паразитом, сделай что-нибудь самостоятельно!
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #10 : 13.01.2015, 23:46:13 »
Ошибка
Сохранить не удалось из-за ошибки:   - это в админке, когда сохраняю.


вот полностью файл, как я понял есть и внизу этой функиции прописал.

components/com_comp/models/product.php

Код
<?php
/**
* @version $Id: films.php 2015-01-13 16:40:57 Dm $
* @package Comfilms
* @subpackage Models
* @copyright Copyright (C) 2015, Dmitry. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// import Joomla modelitem library
jimport('joomla.application.component.modelitem');

/**
 *  Films Model class for Comfilms Component
 */
class ComfilmsModelFilms extends JModelItem {

/**
* Model context string.
*
* @var string
*/
protected $context = 'com_comfilms.films';

/**
* @var object item
*/
protected $item;

/**
* Method to auto-populate the model state.
*
* This method should only be called once per instantiation and is designed
* to be called on the first call to the getState() method unless the model
* configuration flag to ignore the request is set.
*
* Note. Calling getState in this method will result in recursion.
*
* @return void
* @since 1.6
*/
protected function populateState(){
$app = JFactory::getApplication();

// Load the object state.
$id = JRequest::getInt('id');
$this->setState('films.id', $id);

// Load the parameters.
$params = $app->getParams();
$this->setState('params', $params);
parent::populateState();
}

protected function getStoreId($id = ''){
// Compile the store id.
$id .= ':'.$this->getState('films.id');
return parent::getStoreId($id);
}

/**
* Returns a reference to the a Table object, always creating it.
*
* @param type The table type to instantiate
* @param string A prefix for the table class name. Optional.
* @param array Configuration array for model. Optional.
* @return JTable A database object
* @since 1.6
*/
public function getTable($type = 'Film', $prefix = 'ComfilmsTable', $config = array()){
return JTable::getInstance($type, $prefix, $config);
}

/**
     * Load an JSON string into the registry into the given namespace [or default if a namespace is not given]
     *
     * @param    string    JSON formatted string to load into the registry
     * @return    boolean True on success
     * @since    1.5
     * @deprecated 1.6 - Oct 25, 2010
     */
    public function loadJSON($data){
        return $this->loadString($data, 'JSON');
    }

/**
* Method to get Film data.
*
* @param integer The id of the films.
*
* @return mixed item data object on success, false on failure.
*/
public function getItem($id = null){
if (!isset($this->item)){
$id = $id?$id:$this->getState('films.id');
//Get a table instance.
$table = JTable::getInstance('Film', 'ComfilmsTable');

//Attempt to load the row.
if($table->load($id)){
// Convert the JTable to a clean JObject.
$dataArray = $table->getProperties(1);
$this->item = JArrayHelper::toObject($dataArray, 'JObject');
}elseif($error = $table->getError()){
$this->setError($error);
return false;
}
}
return $this->item;

if ( $item = parent::getItem( $id ) ) {
$item->city = trim( $item->city) === '' ? array() : json_decode( trim( $item->city) );
}
return $item;
}

/**
* Build an SQL query to load the list data.
*
* @return  JDatabaseQuery
* @since   1.6
*/
protected function getListQuery(){
$db = $this->getDbo();
$query = $db->getQuery(true);

// Select the required fields from the table.
$query->select(
$this->getState(
'list.select',
'a.taguss, a.name, a.kartinka, a.city, a.kogda, a.short_description, a.description, a.published, a.checked_out, a.checked_out_time, a.ordering, a.id'
)
);
$query->from($db->quoteName('#__comfilms_films').' AS a');

// Join over the Cities.
$query->select('city.name AS city_title, city.id AS city_id');
$query->join('LEFT', '#__comfilms_city AS city ON city.id = a.city');

// Filter by City.
$cityId = $this->getState('filter.city_id');
if (is_numeric($cityId)){
$query->where('a.city = '.(int) $cityId);
}

// Join over the users for the checked out user.
$query->select('uc.name AS uc_editor');
$query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');



// Filter by published state
$published = $this->getState('filter.state');
if (is_numeric($published)){
$query->where('a.published = '.(int) $published);
} elseif ($published === ''){
$query->where('(a.published IN (0, 1))');
}


// Filter by search in title
$search = $this->getState('filter.search');
if(!empty($search)){
if (stripos($search, 'id:') === 0){
$query->where('a.id = '.(int) substr($search, 3));
}else{
$search = $db->Quote('%'.$db->escape($search, true).'%');
$query->where('(a.name LIKE '.$search.')');
}
}

// Add the list ordering clause.
$orderCol = $this->state->get('list.ordering', 'ordering');
$orderDirn = $this->state->get('list.direction', 'ASC');
/*if ($orderCol == 'ordering' || $orderCol == 'category_title'){
$orderCol = 'c.title '.$orderDirn.', a.ordering';
}*/

$query->order($db->escape($orderCol.' '.$orderDirn));

//echo nl2br(str_replace('#__','jos_',$query));
return $query;
}

/**
* Method to get Films data.
*
*
* @return array array of item data objects on success, empty array on failure.
*/
public function getItems(){
$db = $this->getDbo();
$db->setQuery($this->getListQuery());
return $db->loadObjectList();
}
}

« Последнее редактирование: 13.01.2015, 23:51:21 от baskethome »
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Re: Множественный выбор в компоненте
« Ответ #11 : 13.01.2015, 23:50:36 »
Спойлер
[свернуть]
Разберитесь с $this-> item и $item. И return не иполняется 2 раза.

P.S. И вообще, это лишнее
Спойлер
[свернуть]

Только сейчас увидел: вы сохраняете в админке, тогда зачем выкладывали модель из фронта? В модели, где данные сохраняются,
есть модифицированный метод getItem()?

 
« Последнее редактирование: 14.01.2015, 00:06:22 от robert »
Не будь паразитом, сделай что-нибудь самостоятельно!
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #12 : 14.01.2015, 00:13:03 »
administrator/components/com_comp/models/product.php ?

Да.
Код
<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_comfilms
 *
* @copyright Copyright (C) 2015, Dmitry. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

defined('_JEXEC') or die;

/**
 * Banner model.
 *
 * @package     Joomla.Administrator
 * @subpackage  com_comfilms
 * @since       1.6
 */
class ComfilmsModelFilm extends JModelAdmin {
/**
* @var    string  The prefix to use with controller messages.
* @since  1.6
*/
protected $text_prefix = 'COM_COMFILMS_FILM';

/**
* Method to perform batch operations on an item or a set of items.
*
* @param   array   $commands   An array of commands to perform.
* @param   array   $pks        An array of item ids.
* @param   array   $contexts   An array of item contexts.
*
* @return  boolean   Returns true on success, false on failure.
*
* @since 2.5
*/
public function batch($commands, $pks, $contexts){
// Sanitize user ids.
$pks = array_unique($pks);
JArrayHelper::toInteger($pks);

// Remove any values of zero.
if(array_search(0, $pks, true)){
unset($pks[array_search(0, $pks, true)]);
}

if(empty($pks)){
$this->setError(JText::_('JGLOBAL_NO_ITEM_SELECTED'));
return false;
}

$done = false;

if(!empty($commands['category_id'])){
$cmd = JArrayHelper::getValue($commands, 'move_copy', 'c');

if($cmd == 'c'){
$result = $this->batchCopy($commands['category_id'], $pks, $contexts);
if(is_array($result)){
$pks = $result;
}else{
return false;
}
}elseif($cmd == 'm' && !$this->batchMove($commands['category_id'], $pks, $contexts)){
return false;
}
$done = true;
}

if(!$done){
$this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION'));
return false;
}

// Clear the cache
$this->cleanCache();

return true;
}


/**
* Batch copy items to a new category or current.
*
* @param   integer  $value     The new category.
* @param   array    $pks       An array of row IDs.
* @param   array    $contexts  An array of item contexts.
*
* @return  mixed  An array of new IDs on success, boolean false on failure.
*
* @since 2.5
*/
protected function batchCopy($value, $pks, $contexts){
$categoryId = (int) $value;

$table = $this->getTable();
$i = 0;

// Check that the category exists
if ($categoryId){
$categoryTable = JTable::getInstance('Category');
if (!$categoryTable->load($categoryId)){
if ($error = $categoryTable->getError()){
// Fatal error
$this->setError($error);
return false;
}else{
$this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_MOVE_CATEGORY_NOT_FOUND'));
return false;
}
}
}

if (empty($categoryId)){
$this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_MOVE_CATEGORY_NOT_FOUND'));
return false;
}

// Check that the user has create permission for the component
$user = JFactory::getUser();
if (!$user->authorise('core.create', 'com_comfilms.category.' . $categoryId)){
$this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_CREATE'));
return false;
}

// Parent exists so we let's proceed
while (!empty($pks)){
// Pop the first ID off the stack
$pk = array_shift($pks);

$table->reset();

// Check that the row actually exists
if (!$table->load($pk)){
if ($error = $table->getError()){
// Fatal error
$this->setError($error);
return false;
}else{
// Not fatal error
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk));
continue;
}
}

// Alter the title & alias
$data = $this->generateNewTitle($categoryId, $table->alias, $table->name);
$table->name = $data['0'];
$table->alias = $data['1'];

// Reset the ID because we are making a copy
$table->id = 0;


// TODO: Deal with ordering?
//$table->ordering = 1;

// Check the row.
if (!$table->check()){
$this->setError($table->getError());
return false;
}

// Store the row.
if (!$table->store()){
$this->setError($table->getError());
return false;
}

// Get the new item ID
$newId = $table->get('id');

// Add the new ID to the array
$newIds[$i] = $newId;
$i++;
}

// Clean the cache
$this->cleanCache();

return $newIds;
}
/**
* Method to test whether a record can be deleted.
*
* @param   object  $record  A record object.
*
* @return  boolean  True if allowed to delete the record. Defaults to the permission set in the component.
*
* @since   1.6
*/
protected function canDelete($record){
if (!empty($record->id)){
if ($record->published != -2){
return;
}

return parent::canDelete($record);
}
}
/**
* Method to test whether a record can have its state changed.
*
* @param   object  $record  A record object.
*
* @return  boolean  True if allowed to change the state of the record. Defaults to the permission set in the component.
*
* @since   1.6
*/
protected function canEditState($record){
$user = JFactory::getUser();

// Check against the category.
if (!empty($record->category_id)){
return $user->authorise('core.edit.state', 'com_comfilms.category.' . (int) $record->category_id);
}else{// Default to component settings if category not known.
return parent::canEditState($record);
}
}

/**
* Returns a JTable object, always creating it.
*
* @param   string  $type    The table type to instantiate. [optional]
* @param   string  $prefix  A prefix for the table class name. [optional]
* @param   array   $config  Configuration array for model. [optional]
*
* @return  JTable  A database object
*
* @since   1.6
*/
public function getTable($type = 'Film', $prefix = 'ComfilmsTable', $config = array()){
return JTable::getInstance($type, $prefix, $config);
}

/**
* Method to get the record form.
*
* @param   array    $data      Data for the form. [optional]
* @param   boolean  $loadData  True if the form is to load its own data (default case), false if not. [optional]
*
* @return  mixed  A JForm object on success, false on failure
*
* @since   1.6
*/
public function getForm($data = array(), $loadData = true){
// Get the form.
$form = $this->loadForm('com_comfilms.film', 'film', array('control' => 'jform', 'load_data' => $loadData));
if(empty($form)){
return false;
}

// Determine correct permissions to check.
if ($this->getState('film.id')){
// Existing record. Can only edit in selected categories.
$form->setFieldAttribute('catid', 'action', 'core.edit');
}else{
// New record. Can only create in selected categories.
$form->setFieldAttribute('catid', 'action', 'core.create');
}

// Modify the form based on access controls.
if (!$this->canEditState((object) $data)){
// Disable fields for display.
$form->setFieldAttribute('ordering', 'disabled', 'true');
$form->setFieldAttribute('publish_up', 'disabled', 'true');
$form->setFieldAttribute('publish_down', 'disabled', 'true');
$form->setFieldAttribute('state', 'disabled', 'true');

// Disable fields while saving.
// The controller has already verified this is a record you can edit.
$form->setFieldAttribute('ordering', 'filter', 'unset');
$form->setFieldAttribute('publish_up', 'filter', 'unset');
$form->setFieldAttribute('publish_down', 'filter', 'unset');
$form->setFieldAttribute('state', 'filter', 'unset');
}

return $form;
}

/**
* Method to get the data that should be injected in the form.
*
* @return  mixed  The data for the form.
*
* @since   1.6
*/
protected function loadFormData(){
// Check the session for previously entered form data.
$app  = JFactory::getApplication();
$data = $app->getUserState('comfilms.edit.film.data', array());

if(empty($data)){
$data = $this->getItem();

// Prime some default values.
if($this->getState('film.id') == 0){
$data->set('catid', $app->input->getInt('catid', $app->getUserState('com_comfilms.films.filter.category_id')));
}

// bands
if($data->taguss){
$data->taguss = explode(',', $data->taguss);
}

// city
if($data->city){
$data->city = explode(',', $data->city);
}
}

return $data;
}

public function save( $data ){
$data['city'] = json_encode( $data['city'] );
parent::save( $data );

}

/*protected function loadFormData(){
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_MYCOMPONENT.edit.MYVIEW.data', array());
if (empty($data)){
$data = $this->getItem();
};
// bands
if($data->taguss){
$data->taguss = explode(',', $data->taguss);
}
return $data;
}
*/
/**
* A protected method to get a set of ordering conditions.
*
* @param   JTable  $table  A record object.
*
* @return  array  An array of conditions to add to add to ordering queries.
*
* @since   1.6
*/
protected function getReorderConditions($table){
$condition = array();
$condition[] = 'catid = '. (int) $table->catid;
$condition[] = 'state >= 0';
return $condition;
}

/**
* @since  3.0
*/
protected function prepareTable($table){
$date = JFactory::getDate();
$user = JFactory::getUser();

if (empty($table->id)){
// Set the values
$table->created = $date->toSql();
// Set ordering to the last item if not set
if (empty($table->ordering)){
$db = JFactory::getDbo();
$db->setQuery('SELECT MAX(ordering) FROM #__comfilms_films');
$max = $db->loadResult();

$table->ordering = $max + 1;
}
}else{
// Set the values
$table->modified = $date->toSql();
$table->modified_by = $user->get('id');
}
}
}

*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Re: Множественный выбор в компоненте
« Ответ #13 : 14.01.2015, 00:21:14 »
Да, туда и добавьте getItem().
Не будь паразитом, сделай что-нибудь самостоятельно!
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #14 : 14.01.2015, 00:32:33 »
Добавил, но теперь вообще всё пустое сохраняется(((
Код
public function getItem( $id = null ){
if ( $item = parent::getItem( $id ) ) {
$item->city = trim( $item->city) === '' ? array() : json_decode( trim( $item->city) );
}
return $item;
}
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #15 : 14.01.2015, 00:49:04 »
вот ссылка на тестовый компонент по этой теме http://developerextensions.com/components/com_jcc/arc/503/com_comfilms-0.0.0.1..3.zip Может это больше поможет. очень нужна помощь
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Re: Множественный выбор в компоненте
« Ответ #16 : 14.01.2015, 00:53:12 »
Вместо "taguss" вы написали "city". Сообщение об ошибке все еще вылезает, но item сохраняется.
Код: php-brief
public function getItem( $id = null ){
if($item = parent::getItem( $id ) ) {
$item->taguss = trim( $item->taguss) === '' ? array() : json_decode( trim( $item->taguss) );
}
return $item;
}

public function save( $data ){
$data['taguss'] = json_encode( $data['taguss'] );
return parent::save( $data );
}
Вот теперь без ошибок.
« Последнее редактирование: 14.01.2015, 01:50:15 от robert »
Не будь паразитом, сделай что-нибудь самостоятельно!
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #17 : 14.01.2015, 00:58:11 »
вы уж меня извините, не силен в php, тока учусь. Вроде делаю все как пишите, но опять выводит Ошибка! Сохранить не удалось из-за ошибки:
Может исходник всего компонента посмотрите, может я что-то не так объяснил...
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #18 : 14.01.2015, 01:45:10 »
не работает. Мне нужен city. В компоненте 2 таблицы (город и продукт). в продукте должен работать множественный выбор города (который подтягивается из таблицы городов), но чё то он не хочет работать
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Re: Множественный выбор в компоненте
« Ответ #19 : 14.01.2015, 01:52:49 »
Спойлер
[свернуть]
Какой тут city?
Вместо "taguss" вы написали "city". Сообщение об ошибке все еще вылезает, но item сохраняется. Вот теперь без ошибок.
Код: php-brief
public function getItem( $id = null ){
if($item = parent::getItem( $id ) ) {
$item->taguss = trim( $item->taguss) === '' ? array() : json_decode( trim( $item->taguss) );
}
return $item;
}

public function save( $data ){
$data['taguss'] = json_encode( $data['taguss'] );
return parent::save( $data );
}
Не будь паразитом, сделай что-нибудь самостоятельно!
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #20 : 14.01.2015, 01:59:48 »
taguss это я просто может показывал, что получилось вывести, а вот чтобы был множественный выбор города не получается
Код
<field
id="city"
name="city"
multiple="1"
required="false"
type="comfilmsCities"
label="COM_COMFILMS_FIELD_CITY_LABEL"
description="COM_COMFILMS_FIELD_CITY_DESC"
size="40"/>

targuss получилось вывести с помощью этой статьи http://blog.calebnance.com/joomla-3.0/saving-a-multi-select-field-in-a-custom-joomla-3.x-component.html
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Re: Множественный выбор в компоненте
« Ответ #21 : 14.01.2015, 02:12:29 »
У вас в БД тип поля "city": int(10), а должен быть текстовым. Короче, я пойду спать, а то скоро за вас все сделаю.
Не будь паразитом, сделай что-нибудь самостоятельно!
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #22 : 14.01.2015, 02:26:38 »
да вроде как varchar стоит. Спасибо.
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #23 : 14.01.2015, 09:28:25 »
сколько будет стоить дописать чуть-чуть как мне надо?
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Re: Множественный выбор в компоненте
« Ответ #24 : 14.01.2015, 09:31:38 »
А что вам надо?
Не будь паразитом, сделай что-нибудь самостоятельно!
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #25 : 14.01.2015, 10:05:53 »
надо доработать компонент из 2 таблиц: продукт и город, чтобы в продукте в поле город можно было сделать множественный выбор городов
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Re: Множественный выбор в компоненте
« Ответ #26 : 14.01.2015, 11:18:08 »
Так и сейчас уже работает, см. пред. сообщения.
Не будь паразитом, сделай что-нибудь самостоятельно!
*

baskethome

  • Захожу иногда
  • 110
  • 0 / 0
Re: Множественный выбор в компоненте
« Ответ #27 : 14.01.2015, 11:31:32 »
не работает. Работает обычный мультиселект с помощью этой статьи http://blog.calebnance.com/joomla-3.0/saving-a-multi-select-field-in-a-custom-joomla-3.x-component.html
мне же надо, чтобы работал мультивыбор поля город, который подтягивает данные (название) из 2-ой таблицы. он не сохраняет, уже как тока не пробовал.
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Re: Множественный выбор в компоненте
« Ответ #28 : 14.01.2015, 13:15:13 »
Не работает другое, а мультивыбор по последней редакции кода как раз работает. Ладно, стукните по Skype: npnrus.
Не будь паразитом, сделай что-нибудь самостоятельно!
*

AlekVolsk

  • Гуру
  • 6913
  • 416 / 4
Re: Множественный выбор в компоненте
« Ответ #29 : 14.01.2015, 17:35:53 »
чтобы работал мультивыбор поля город, который подтягивает данные (название) из 2-ой таблицы
Чтобы выбрать несколько значений и хранить их в одном поле? А в каком виде они хранятся в базе и каков тип поле, где хранятся эти значения?
Чтобы оставить сообщение,
Вам необходимо Войти или Зарегистрироваться
 

MySQL Что быстрее выбор столбца в таблице с кучей столбцов или с 1?

Автор platonische

Ответов: 2
Просмотров: 629
Последний ответ 22.10.2020, 15:28:19
от platonische
Обработка AJAX в компоненте Joomla!3

Автор balancer

Ответов: 33
Просмотров: 11921
Последний ответ 23.07.2020, 07:45:53
от Dolphin4ik_1
Пагинатор в нестандартном компоненте

Автор sesil

Ответов: 8
Просмотров: 1281
Последний ответ 04.09.2019, 11:24:30
от sesil
Не видится файлы языкового пакета в созданном компоненте

Автор khachatur86

Ответов: 0
Просмотров: 1717
Последний ответ 30.03.2019, 23:35:26
от khachatur86
Стандартная система рейтингов в custom компоненте

Автор platonische

Ответов: 1
Просмотров: 1014
Последний ответ 12.02.2019, 16:55:03
от platonische