Quantcast
Channel: Yii Framework Forum
Viewing all 18717 articles
Browse latest View live

Problemas no gii

$
0
0
Eu estava mexendo nos códigos gerados pelo gii e acabei fazendo "merda", então como ainda estou no começo do projeto deletei ele e criei outro, após fazer toda conexão com banco e gerar novamente os códigos ele fia dando esse erro:

PHP warning

htmlspecialchars() expects parameter 1 to be string, resource given

C:\xampp\htdocs\yii\framework\web\helpers\CHtml.php(103)


antes funcionava normalmente o formulário, quando eu mexi no código e buguei eu deletei o projeto e criei outra vez mas o erro persiste

  • : 2.png
  • : 1.png
  • : 3.png
  • : 4.png

Tabs com action update / create

$
0
0
Bom dia.

Tenho de criar vários formulários dentro de tabs, tendo optado pelo CJuiTabs. Até eu consigo sem problema.
O meu problema está que em dois desses forms, um é para fazer update ao model Objectivos e o outro é para criar registos no mesmo model Objectivos recorrendo ao DynamicTabular Input.
Ao criar o formulário para o dynamicTabular Input tenho de criar um array do model objectivos, o que quando faço guardar gera um erro e não grava.
Os meus tabs:

<?php
$form=$this->beginWidget('DynamicTabularForm',array(
'id'=>'default-parent-form',
'enableAjaxValidation'=>false,
));

?>
<?php
$tabs['Dados Pessoais']=array(
'id'=>'dataFielsTab',
'content'=>$this->renderPartial('_formPag1',array(
'form'=>$form,
'model1'=>$model1,
'model2'=>$model2,
'colaborador'=>$colaborador,
),
true)
);

$tabs['Competências']=array(
'id'=>'dataFielsCompet',
'content'=>$this->renderPartial('_formPag2',array(
'form'=>$form,
'items'=>$itemsCompet,
'modelCompet'=>$modelCompet,
'compet'=>$compet,
),
true)
);
$tabs['Objectivos Ano Anterior']=array(
'id'=>'dataFielsObj',
'content'=>$this->renderPartial('_formPag3',array(
'form'=>$form,
'items'=>$items,
'model'=>$model,
),
true)
);


$tabs['Novos Objectivos']=array(
'id'=>'definirObj',
'content'=>$this->renderPartial('_formPag4',array(
'form'=>$form,
'obj'=>$obj,


),
true)
);

$tabs['Acção de Formação']=array(
'id'=>'formacao',
'content'=>$this->renderPartial('_formPag5',array(
'form'=>$form,
'forma'=>$forma,

),
true)
);
$tabs['Resultado']=array(
'id'=>'resultado',
'content'=>$this->renderPartial('_formPag6',array(
'form'=>$form,

),
true)
);
$tabs['Comentários']=array(
'id'=>'comentarios',
'content'=>$this->renderPartial('_formPag7',array(
'form'=>$form,
'momento'=>$momento,

),
true)
);



$this->widget('zii.widgets.jui.CJuiTabs',array(
'tabs'=>$tabs,
'options'=>array(
'collapsible'=>false,
),
));


?>
<br>
<div style="margin-left: 930px">
<?php

$this->widget('zii.widgets.jui.CJuiButton',array(

'name'=>'submit',

'caption'=>'Enviar',

'htmlOptions'=>array(

'style'=>'background:#006600;color:#ffffff;',

),

));

?>

No meu controller tenho o $model= new Objectivos('areaColaborador');
e $obj= array(new Objectivos());
Como é que posso contornar esta situação?
O update é realizado pelo tabular input que tem na documentação do Yii.

Obrigada.

Prevent Content overwriting in CMS

$
0
0
Hey Guys,

I have developed a content management system using the Yii framework. Since a lot of users have access to the same content , the content gets overwritten when more than one user access the content and try to modify it around the same time.

I am constantly thinking about a way of solving this or is there any extensions or plugins I could use you guys are aware of. Let me know.

Thanks

Каким способ вывести категории из БД?

$
0
0
Какие есть способы вывести категории из базы данных по id?

Inner join mysql y yii 2.

$
0
0
Hola chicos este es mi metodo del controlador y funcionaba con una sola tabla pero con dos no.
Que es lo que esta conceptualmente mal?


 public function actionAbout()
    {
        $table= new t_complejos;
        $model = $table->find()->all();
        $model2 = $table2->find()->all();
        $table2 = new t_canchas;
        $form= new formBusqueda;
        $search = null;
        
        if($form->load(Yii::$app->request->get()))
        {
            if ($form->validate())
            {
             $search = Html::encode($form->q);
                $query = "SELECT * FROM t_complejos inner join t_canchas on t_complejos.id_complejos = t_canchas.id_cancha '%$search%' OR ";
                $model = $table->findBySql($query)->all();
                $model2 = $table2->findBySql($query)->all();
            }
            else
            {

                $form->getErrors();
            }

        }
        return $this->render("about", ["model"=>$model, "form"=>$form, "search"=>$search]);
    }








Yii CGridView change column width for raw type cell

$
0
0
I am using Yii 1.1 CGridView with 'raw' cell type. The cell contains text field generated using CHtml::textField. Here I cannot change the width of the column using headerHtmlOptions or htmlOptions. Please help.

$this->widget('zii.widgets.grid.CGridView', array(
        'id'=>'mbook-grid',
        'itemsCssClass'=>'table table-bordered table-condensed table-hover table-striped dataTable',
        'dataProvider'=>$model->search(),
        'afterAjaxUpdate'=>'calcquantity',
        'enablePagination' => true,
        'pagerCssClass'=>'dataTables_paginate paging_bootstrap table-pagination',
        'pager' => array('header'=>'','htmlOptions'=>array('class'=>'pagination')),
        'columns' => array(

                            array(
                            'class' => 'CCheckBoxColumn',
                            'id'=>'project_estimate_id',
                            'htmlOptions'=>array('style' => 'display:none'),
                            'headerHtmlOptions'=>array('style' => 'display:none'),    
                            'selectableRows'=>2,
                            'value'=>'$data["project_estimate_id"]',
                            'checked'=>'true',
                            ),
                            array(name=>'description','value'=>'CHtml::textField("ProjectMBookGrid[description_".$data["project_estimate_id"]."]",$data["description"],array("class"=>"gridfield"))','type'=>'raw','header'=>'Description','headerHtmlOptions'=>array('style'=>'width: 5%;')),

                            array(name=>'length','value'=>'CHtml::textField("ProjectMBookGrid[length_".$data["project_estimate_id"]."]",$data["length"],array("class"=>"gridfield","style"=>"text-align: right"))','type'=>'raw','header'=>'Length','headerHtmlOptions'=>array('style'=>'width:5%')),
                            array(name=>'breadth','value'=>'CHtml::textField("ProjectMBookGrid[breadth_".$data["project_estimate_id"]."]",$data["breadth"],array("class"=>"gridfield","style"=>"text-align: right"))','type'=>'raw','header'=>'Breadth','htmlOptions'=>array('style'=>'text-align: right')),

   array(name=>'quantity','value'=>'CHtml::textField("ProjectMBookGrid[quantity_".$data["project_estimate_id"]."]",$data["quantity"],array("class"=>"gridfield","style"=>"text-align: right"))','type'=>'raw','header'=>'Quantity','htmlOptions'=>array('style'=>'text-align: right')),

            ),
                'htmlOptions'=>array('class'=>'grid-view table-responsive hide-x-scroll'),
    ))

Tracking for Web

$
0
0
Tracking4Web is the solution for Small and Medium Courier & Cargo Businesses, simple application that will help you track and manage every cargo in the company

Features Included:

Category Management
Shipment Management
Client Track & Trace Management
REST API Support
Source Code Modification

http://demo.tracking4web.bryantan.info/backend

  • : Screen-Shot-2014-08-02-at-5.17.56-PM.png
  • : Screen-Shot-2014-08-02-at-5.16.19-PM.png

CGridView with CStarRating filtering

$
0
0
Hi,

I have a problem with CstarRating in my CGridView. It's not working when I'm trying to filtering the data. When I try to click for example two stars - nothing happens. Not filtering.

Code:

array(
'name'=>'rating',
'type'=>'raw',
'value'=>'$this->grid->controller->widget("CStarRating",
array("starCount"=>"5",
"minRating"=>"1",
"maxRating"=>"5",
"name"=>$data->id,
"value"=>$data->rating,
"readOnly"=>true,
"id"=>"rating_" . $data->id,
"htmlOptions"=>array(\'class\'=>\'StarRating\'),
),true)',

'filter'=>$this->widget('CStarRating',array(
'name'=>'TblPrograms[rating]',
'id'=>'TblPrograms_rating',
'starCount' => '5',
'minRating' => '1',
'maxRating' => '5',

), true),
),

HTML generated:
<span id="TblPrograms_rating">
<span class="star-rating-control"><div class="rating-cancel"><a title="Cancel Rating"></a></div><div class="star-rating rater-0 star-rating-applied star-rating-live star-rating-on" id="TblPrograms_rating_0"><a title="1">1</a></div><div class="star-rating rater-0 star-rating-applied star-rating-live star-rating-on" id="TblPrograms_rating_1"><a title="2">2</a></div><div class="star-rating rater-0 star-rating-applied star-rating-live" id="TblPrograms_rating_2"><a title="3">3</a></div><div class="star-rating rater-0 star-rating-applied star-rating-live" id="TblPrograms_rating_3"><a title="4">4</a></div><div class="star-rating rater-0 star-rating-applied star-rating-live" id="TblPrograms_rating_4"><a title="5">5</a></div></span><input id="TblPrograms_rating_0" value="1" type="radio" name="TblPrograms[rating]" class="star-rating-applied" style="display: none;">
<input id="TblPrograms_rating_1" value="2" type="radio" name="TblPrograms[rating]" class="star-rating-applied" style="display: none;" checked="checked">
<input id="TblPrograms_rating_2" value="3" type="radio" name="TblPrograms[rating]" class="star-rating-applied" style="display: none;">
<input id="TblPrograms_rating_3" value="4" type="radio" name="TblPrograms[rating]" class="star-rating-applied" style="display: none;">
<input id="TblPrograms_rating_4" value="5" type="radio" name="TblPrograms[rating]" class="star-rating-applied" style="display: none;">
</span>

Radio buttons (without CStarRating ext) are working but I want to have stars in my filter box.

Please help, I have no idea what is the problem :(

Acces to controller throught layout

$
0
0
Hi.

I would like to know if is possible get a controller method in a layout. Example:

Components/Controller.php
public function welcome(){

return "Hello";

}

views/layout/main.php
echo $this->welcome();


I need to show in the layout the value of the welcome method in controller. How can I do this? This welcome method has to be common to all views also

Thank you!

GUARDAR DATOS MULTIPLES CHECKBOXLIST - EN BASE DE DATOS

$
0
0
Hola a todos los programadores, he creado un proyecto con Gii para generar los modelos y los controladores.
ADJUNTO EL PROYECTO AQUI:  project-gii.zip (391.03K)
: 0

DESEO DESDE EL FORMULARIO DE USUARIO PODER GUARDAR EN LA TABLA RELACION USUARIOS_IDIOMAS los idiomas pertenecientes a un usuario, muchisimas gracias... mas adelante expongo el codigo y las imagenes:

Mi base de datos es la siguiente:
-----------------
USUARIOS |
-----------------
id->PK |
nombre |
apellido |
documento |
direccion |
#id_genero->FK |
#id_profesion->FK |
-------------------


-------------------
GENEROS |
------------------
id->PK |
nombre |
------------------


-------------------
PROFESIONES |
------------------
id->PK |
nombre |
------------------

-------------------
IDIOMAS |
------------------
id->PK |
nombre |
------------------


-------------------
USUARIOS_IDIOMAS |
------------------
#id_usuarios->FK |
#id_idiomas->FK |
------------------


: llenar_tabla_relacion.png





mi idea es que al momento de llenar el formulario para usuario, contenga los checkbox de idiomas, para saber qué idiomas maneja el usuario. Y por medio de esos checkbox guardar los registros en la tabla USER_LANGUAGE

pero realmente no se como hacer para que esto suceda.
Alguien me puede colaborar?


Model ---> Usuario.php

<?php

/**
 * This is the model class for table "usuarios".
 *
 * The followings are the available columns in table 'usuarios':
 * @property integer $id
 * @property string $nombre
 * @property string $apellido
 * @property string $documento
 * @property string $direccion
 * @property integer $idGenero
 * @property integer $idProfesion
 */
class Usuario extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Usuario the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'usuarios';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('nombre, apellido, documento, direccion, idGenero, idProfesion', 'required'),
			array('idGenero, idProfesion', 'numerical', 'integerOnly'=>true),
			array('nombre, apellido, direccion', 'length', 'max'=>250),
			array('documento', 'length', 'max'=>20),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, nombre, apellido, documento, direccion, idGenero, idProfesion', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	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(

			'genero'=>array(self::BELONGS_TO,'Genero','idGenero'),
			'profesion'=>array(self::BELONGS_TO,'Profesion','idProfesion'),
			'idiomas'=>array(self::MANY_MANY,'Idioma', 'usuarios_idiomas(id_usuarios,id_idiomas)'),

		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'nombre' => 'Nombre',
			'apellido' => 'Apellido',
			'documento' => 'Documento',
			'direccion' => 'Direccion',
			'idGenero' => 'Id Genero',
			'idProfesion' => 'Id Profesion',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('nombre',$this->nombre,true);
		$criteria->compare('apellido',$this->apellido,true);
		$criteria->compare('documento',$this->documento,true);
		$criteria->compare('direccion',$this->direccion,true);
		$criteria->compare('idGenero',$this->nombre);
		$criteria->compare('idProfesion',$this->nombre);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
}






controller -> UsuarioController.php

<?php

class UsuarioController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Usuario;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Usuario']))
		{
			$model->attributes=$_POST['Usuario'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Usuario']))
		{
			$model->attributes=$_POST['Usuario'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Usuario');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Usuario('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Usuario']))
			$model->attributes=$_GET['Usuario'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Usuario::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='usuario-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}







USUARIO FORM ---> form_.php

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'usuario-form',
	'enableAjaxValidation'=>false,
));


 ?>

	<p class="note">Fields with <span class="required">*</span> are required.</p>

	<?php echo $form->errorSummary($model); ?>

	<div class="row">
		<?php echo $form->labelEx($model,'nombre'); ?>
		<?php echo $form->textField($model,'nombre',array('size'=>60,'maxlength'=>250)); ?>
		<?php echo $form->error($model,'nombre'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'apellido'); ?>
		<?php echo $form->textField($model,'apellido',array('size'=>60,'maxlength'=>250)); ?>
		<?php echo $form->error($model,'apellido'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'documento'); ?>
		<?php echo $form->textField($model,'documento',array('size'=>20,'maxlength'=>20)); ?>
		<?php echo $form->error($model,'documento'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'direccion'); ?>
		<?php echo $form->textField($model,'direccion',array('size'=>60,'maxlength'=>250)); ?>
		<?php echo $form->error($model,'direccion'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'Genero'); ?>
		<?php echo $form->radioButtonList($model,'idGenero', CHtml::listData(Genero::model()->findAll(),'id','nombre'), array('separator'=>' ','labelOptions'=>array('style'=>'display:inline'))); ?>
		<?php echo $form->error($model,'idGenero'); ?>
	</div>

	
	<div class="row">
		<?php echo $form->labelEx($model,'Idioma'); ?>
		<?php echo $form->checkBoxList($model,'id', CHtml::listData(Idioma::model()->findAll(),'id','nombre'), array('separator'=>' ','labelOptions'=>array('style'=>'display:inline'))); ?>
		<?php echo $form->error($model,'idIdioma'); ?>
	</div>
	

	<div class="row">
		<?php echo $form->labelEx($model,'Profesion'); ?>
		<?php echo $form->dropDownList($model,'idProfesion',CHtml::listData(Profesion::model()->findAll(),'id','nombre'),array('empty'=>'seleccione una profesión')); ?>
		<?php echo $form->error($model,'idProfesion'); ?>
	</div>

	<div class="row buttons">
		<?php echo CHtml::submitButton($model->isNewRecord ? 'Guardar' : 'Save'); ?>
	</div>

<?php $this->endWidget(); ?>

</div>&lt!-- form -->



: formulario_usuario.png


realmente no me guarda la seleccion del checkbox en la tabla relacion entre usuarios e idiomas... la webapp no genera ningun error pero no cumple con el requerimiento.

espero su pronta respuesta. muchas gracias

Filtrar por fechas CSqlDataProvider

$
0
0
Buenas,

Mi problema es que quiero filtrar un consulta sql entre fechas que entrega el usuario

Mi controlador lo tengo así

public function actionAdmin()
	{

		$desde = date('Y-m-d',strtotime($_POST['fechainicio']));
        $hasta = date('Y-m-d',strtotime($_POST['fechafin']));
        
		$model=new PagosCarterosGeneral('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['PagosCarterosGeneral']))
			$model->attributes=$_GET['PagosCarterosGeneral'];

		  $sql = "SELECT CA.rut AS MAIN_ID, 
	            CA.nombre AS nom, 
	            CA.apellido_paterno AS ap, 
	            CA.apellido_materno AS am, 
	            DA.fecha_devolucion AS fecha,
	            SUM(RE.cantidad_cartas) AS totalC, 
	            SUM(DA.cantidad_devoluciones) AS totalD
				FROM cartero AS CA
				INNER JOIN 
				carga_diaria AS CD
				ON (CD.rut_cartero = CA.rut)
				INNER JOIN registro_acuse AS RE
				ON (CD.codigo_acuse_recibo = RE.codigo_acuse_recibo)
				INNER JOIN devolucion_acuse AS DA
				ON (RE.codigo_acuse_recibo = DA.codigo_acuse_recibo)
				WHERE DA.fecha_devolucion Between '".$desde."' AND '".$hasta."' 
				GROUP BY MAIN_ID, nom, ap, am

				";
        
        $rawData = Yii::app()->db->createCommand($sql);
		$count = Yii::app()->db->createCommand(
                                         'SELECT COUNT(*) FROM (' . $sql . ') as count_alias')->queryScalar();
 
        $model = new CSqlDataProvider($rawData, array( 
                    'keyField' => 'MAIN_ID', 
                    'totalItemCount' => $count,
                    'sort' => array(
                        'attributes' => array(
                            'MAIN_ID','nom','ap','am'
                        ),
                        'defaultOrder' => array(
                            'ap' => CSort::SORT_ASC,
                        ),
                    ),
                    'pagination' => array(
                        'pageSize' => 11,
                    ),
                ));
 
        $this->render('admin', array(
            'model' => $model,
        ));
	}



y mi vista admin así
  
                <b>Desde:</b>
                <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                                        'name'=>'fechainicio',                                                                  
                                        'language' => 'es',                                     
                                        'htmlOptions'=>array(                                           
                                        'readonly'=>"readonly",
                                        ),
                                        'options'=>array(                                               
                                                'dateFormat'=>'dd-mm-yy',                                                       
                                        ),
                )); ?>
              
                <b>Hasta:</b>
                <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                                        'name'=>'fechafin',                                                                     
                                        'language' => 'es',                                     
                                        'htmlOptions'=>array(                                           
                                        'readonly'=>"readonly",
                                        ),
                                        'options'=>array(                                               
                                                'dateFormat'=>'dd-mm-yy',                                                       
                                        ),
                )); ?>

                 <?php echo CHtml::submitButton('Filtrar'); ?>

<?php $this->widget('bootstrap.widgets.TbGridView', array(
    'id' => 'a-grid-id',
    'dataProvider' => $model,
    'ajaxUpdate' => true, 
    'filter' => null, 
    'columns' => array(
        array(
            'header' => 'R.U.T',
            'name' => 'MAIN_ID',
           
        ),
        array(
            'header' => 'Nombre',
            'name' => 'nom',
            'value' => '$data[nom]." ".$data[ap]." ".$data[am]',
           
        ),
        array(
            'header' => 'Cartas',
            'name' => 'totalC',
            //'value'=>'$data["title"]', //in the case we want something custom
        ),
        array(
            'header' => 'Devoluciones',
            'name' => 'totalD',
           
        ),
 
        ),
    )
);?>           


Se que me falta enviar desde la vista admin los parametros $desde y $hasta pero no se como.

De antemano muchas gracias.

Mostrar resultado de una busqueda en mysql.

$
0
0
Hola chicos, como puedo mostrar esto en la vista.
El modelo no esta definido dice, y search como lo puedo definir?

Metodo del controlador

 public function actionAbout()
    {
       
        
        $form= new formBusqueda;
        $search = null;
        
        if($form->load(Yii::$app->request->get()))
        {
            if ($form->validate())
            {
                 $search = Html::encode($form->q);
               
                 $query = new Query;
                 $query	 ->select(['t_complejos.id_complejos'])  
		         ->from('t_complejos')
		         ->join(	'INNER JOIN', 
				't_canchas',
				't_canchas.id_cancha = t_complejos.id_complejos'
			); 

$model = $query->createCommand();
$model = $command->queryAll();	
                 
                 
                 
                 
                
            }
            else
            {

                $form->getErrors();
            }

        }
        return $this->render("about", ["model"=>$model, "form"=>$form, "search"=>$search]);
    }









vista



 <?= $f->field($form, "q")->input("search") ?>
    
    <?= Html::submitButton("buscar", ["class" => "btn btn-primary"]) ?>

</div>
<?php $f->end() ?>








[SOLUCIONADO]Filtro Relacionado a varios modelos en CGridview

$
0
0
Buenas,

Mi problema es el siguiente:

tengo 4 tablas relacionadas entre si de la siguiente forma

Modelo DevolucionAcuse
'codigoAcuseRecibo' => array(self::BELONGS_TO, 'RegistroAcuse', 'codigo_acuse_recibo'),



Modelo RegistroAcuse
'cargaDiarias' => array(self::HAS_MANY, 'CargaDiaria', 'codigo_acuse_recibo'),
'devolucionAcuses' => array(self::HAS_MANY, 'DevolucionAcuse', 'codigo_acuse_recibo'),



Modelo CargaDiaria
'rutCliente' => array(self::BELONGS_TO, 'Cliente', 'rut_cliente'),
'codigoAcuseRecibo' => array(self::BELONGS_TO, 'RegistroAcuse', 'codigo_acuse_recibo'),	



Modelo Cliente
'cargaDiarias' => array(self::HAS_MANY, 'CargaDiaria', 'rut_cliente'),	


Mi problema es que quisiera que en el GridView de la vista admin que pertenece a DevolucionAcuse filtrar desde un listData por rut del Cliente lo cual no logro hacer. Sí puedo mostrar la columna con sus datos pero no agregar el filtro.

Por poner un ejemplo, en el GridView de CargaDiaria tengo lo siguiente

<?php $this->widget('bootstrap.widgets.TbGridView',array(
                   ...
                    array(
			   'name'=>'rut_cliente',
			   'header'=>'R.U.T',
			   'value'=>'$data->rutCliente->rut',
			   'filter'=>CHtml::listData(Cliente::model()->findAll(),'rut','rut'),
			  ),


Lo cual me funciona perfecto porque es muy sencillo hacerlo cuando la relación es directa entre las 2 tablas, pero se me complica cuando tengo que recorrer las 4 para obtener los datos.

Espero haberme explicado bien, de antemano gracias.

[SOLUCIONADO] Ayuda con Script de Validación de RUT

$
0
0
Muy buenas a todos:

Soy muy nuevo en Yii y PHP y tengo una duda que quizás sea bastante básica pero realmente no se como hacerlo.
En mi proyecto los usuarios hacen Login a la aplicación con su número cédula de identidad (en mi país se le llama RUT) y un password, me gustaría validar el RUT al momento de que este lo escriba, lo cual se hace con el siguiente Script que tengo guardado en un block de notas:

function checkRutField(rut)
{
  var tmpstr = "";
  for ( i=0; i < rut.length ; i++ )
    if ( rut.charAt(i) != ' ' && rut.charAt(i) != '.' && rut.charAt(i) != '-' )
      tmpstr = tmpstr + rut.charAt(i);
  rut = tmpstr;
  largo = rut.length;
// [VARM+]
  tmpstr = "";
  for ( i=0; rut.charAt(i) == '0' ; i++ );
  for (; i < rut.length ; i++ )
     tmpstr = tmpstr + rut.charAt(i);
  rut = tmpstr;
  largo = rut.length;
// [VARM-]
  if ( largo < 2 )
  {
    alert("Debe ingresar el rut completo.");
    document.login.rut_aux.focus();
    document.login.rut_aux.select();
    return false;
  }
  for (i=0; i < largo ; i++ )
  {
    if( (rut.charAt(i) != '0') && (rut.charAt(i) != '1') && (rut.charAt(i) !='2') && (rut.charAt(i) != '3') && (rut.charAt(i) != '4') && (rut.charAt(i) !='5') && (rut.charAt(i) != '6') && (rut.charAt(i) != '7') && (rut.charAt(i) != '8') && (rut.charAt(i) != '9') && (rut.charAt(i) !='k') && (rut.charAt(i) != 'K') )
    {
      alert("El valor ingresado no corresponde a un R.U.T valido.");
      document.login.rut_aux.focus();
      document.login.rut_aux.select();
      return false;
    }
  }
  var invertido = "";
  for ( i=(largo-1),j=0; i>=0; i--,j++ )
    invertido = invertido + rut.charAt(i);
  var drut = "";
  drut = drut + invertido.charAt(0);
  drut = drut + '-';
  cnt = 0;
  for ( i=1,j=2; i<largo; i++,j++ )
    {
    if ( cnt == 3 )
    {
      drut = drut + '.';
      j++;
      drut = drut + invertido.charAt(i);
      cnt = 1;
    }
    else
    {
      drut = drut + invertido.charAt(i);
      cnt++;
    }
  }
  invertido = "";
  for ( i=(drut.length-1),j=0; i>=0; i--,j++ )
    invertido = invertido + drut.charAt(i);
  document.login.rut_aux.value = invertido;
  if(!checkDV(rut))
    return false;
  return true;
}

function checkDV(crut)
{
  largo = crut.length;
  if(largo < 2){
    alert("Debe ingresar el rut completo.");
    document.login.rut_aux.select();
    document.login.rut_aux.focus();
    return false;
  }
  if(largo > 2){
    rut = crut.substring(0, largo - 1);
  }
  else{
    rut = crut.charAt(0);
  }
  dv = crut.charAt(largo-1);

  if(!checkCDV(dv))
     return false;

  if(rut == null || dv == null){
      return false;
  }

  var dvr = '0';
  suma = 0;
  mul  = 2;
  for (i= rut.length -1 ; i >= 0; i--){
    suma = suma + rut.charAt(i) * mul;
    if(mul == 7){
      mul = 2;
    }
    else{
      mul++;
    }
  }
  res = suma % 11;
  if (res==1){
    dvr = 'k';
  }
  else{
    if(res==0){
      dvr = '0';
    }
    else{
      dvi = 11-res;
      dvr = dvi + "";
    }
  }
  if(dvr != dv.toLowerCase()){
    alert("EL rut es incorrecto.");
    document.login.rut_aux.select();
    document.login.rut_aux.focus();
    //document.login.rut_aux.value = "";
    return false;
  }
  return true;
}

function checkCDV(dvr)
{
  dv = dvr + "";
  if(dv != '0' && dv != '1' && dv != '2' && dv != '3' && dv != '4' && dv != '5' && dv != '6' && dv != '7' && dv != '8' && dv != '9' && dv != 'k'  && dv != 'K'){
    alert("Debe ingresar un digito verificador valido.");
    document.login.rut_aux.select();
    document.login.rut_aux.focus();
    return false;
  }
  return true;
}


function checkAll(){ 

	rut_val = document.login.rut_aux.value;  
	if(rut_val.length == 0){         
	    alert("Ingrese su R.U.T.");
        document.login.rut_aux.select();
	    document.login.rut_aux.focus();
	    return;
	}
	if(!checkRutField(document.login.rut_aux.value)){  
      //  document.login.rut_aux.select();
	 //   document.login.rut_aux.focus();
	    return;
	}

  if(document.login.clv.value.length == 0){
    alert("Debes ingresar tu Clave");
	 document.login.clv.select();
	 document.login.clv.focus();
     return;
  }
  if (document.login.clv.value.length != 6){
    alert("La clave a ingresar corresponde a la clave alfanumérica de 6 caracteres, la misma que utilizas cuando llamas al 600 5 242424");
	 document.login.clv.select();
	 document.login.clv.focus();
    return;
  }

	var tmpstr = "";
  	for(i=0; i < rut_val.length ; i++){
    	if(rut_val.charAt(i) != ' ' && rut_val.charAt(i) != '.' && rut_val.charAt(i) != '-'){
      		tmpstr = tmpstr + rut_val.charAt(i);
      	}
    }
    rut_val = tmpstr;
    rut_valor = rut_val.substring(0,rut.length);

  document.login.rut.value = rut_val.substring(0,rut.length);
  document.login.dig.value = rut_val.substring(rut.length,rut.length+1);	
  document.login.rut_aux.value = "";

  document.login.clv.value = document.login.clv.value.toUpperCase();
  document.login.dig.value = document.login.dig.value.toUpperCase();
 
  document.login.clave.value = document.login.clv.value; 
  document.login.clv.value = "";
 
  document.login.submit();
}


Mi problema es que no se donde se pone dicho script o si tengo que guardarlo con alguna extensión en particular,
ni como llamar la función checkRutField(rut) para pasarle como parámetro el username que es de donde voy a tomar el RUT que ingrese el usuario.

De antemano Muchas gracias.

[SOLUCIONADO] Tabla CGridView a partir de SQL

$
0
0
Buenas a todos,

Quiero crear un tabla CGridview a partir de una consulta SQL la cual es la siguiente:

SELECT CA.rut AS MAIN_ID, 
	            CA.nombre AS nom, 
	            CA.apellido_paterno AS ap, 
	            CA.apellido_materno AS am, 
	            SUM(RA.cantidad_cartas) AS totalC, 
	            SUM(DA.cantidad_devoluciones) AS totalD
				FROM cartero AS CA
				INNER JOIN 
				carga_diaria AS CD
				ON (CD.rut_cartero = CA.rut)
				INNER JOIN registro_acuse AS RE
				ON (CD.codigo_acuse_recibo = RE.codigo_acuse_recibo)
				INNER JOIN devolucion_acuse AS DA
				ON (RA.codigo_acuse_recibo = DA.codigo_acuse_recibo)	
				GROUP BY id, nom, ap, am 
				ORDER BY ap DESC


En mi controlador tengo esto:
public function actionPagos() {
        
        $sql = "SELECT CA.rut AS MAIN_ID, 
	            CA.nombre AS nom, 
	            CA.apellido_paterno AS ap, 
	            CA.apellido_materno AS am, 
	            SUM(RA.cantidad_cartas) AS totalC, 
	            SUM(DA.cantidad_devoluciones) AS totalD
				FROM cartero AS CA
				INNER JOIN 
				carga_diaria AS CD
				ON (CD.rut_cartero = CA.rut)
				INNER JOIN registro_acuse AS RE
				ON (CD.codigo_acuse_recibo = RE.codigo_acuse_recibo)
				INNER JOIN devolucion_acuse AS DA
				ON (RA.codigo_acuse_recibo = DA.codigo_acuse_recibo)	
				GROUP BY id, nom, ap, am 
				ORDER BY ap DESC";
        
        $rawData = Yii::app()->db->createCommand($sql)->queryAll();

        $arrayDataProvider = new CArrayDataProvider($rawData, array(
								   'keyField' => 'MAIN_ID',                // PRIMARY KEY
								   'id' => 'Pagos'   // ID of the data provider itself
								));
								        
        $this->render('Pagos', array(
            'arrayDataProvider'=>$arrayDataProvider
        ));
    }


y en vista admin.php tengo lo siguiente:
<?php 
$this->widget('zii.widgets.grid.CGridView', array(
                'id'=>'data-grid',
                'dataProvider'=>$arrayDataProvider,                     
                'columns'=>array(
		                        array(
			                        'header'=>'R.U.T',
			                        'name'=>'MAIN_ID',
			                        'value'=>'$data["id"]'
		                        	),
		                        array(
			                        'header'=>'Nombre',
			                        'name'=>'nom',
			                        'value'=>'$data["nom"]'
		                        	),
		                        array(
			                        'header'=>'Apellido',
			                        'name'=>'ap',
			                        'value'=>'$data["ap"]." ".$data["am"]'
			                        ),
		                        array(
			                        'header'=>'Cantidad',
			                        'name'=>'totalC',
			                        'value'=>'$data["totalC"]'
			                        ),
		                        array(
			                        'header'=>'Devoluciones',
			                        'name'=>'totalD',
			                        'value'=>'$data["totalD"]'
			                        ),
		                        ),
                ));?>       


El problema es que al cargar la página me muestra el error La propiedad "dataProvider" no puede estar vacia.

No sé como arreglar ese problema, o si hay una forma mejor de crear una tabla a partir de una sentencia SQL.

De antemano, gracias por su ayuda

image controller.php get all images php myadmin

$
0
0
no need for help now managed to figure it out
not sure how to delete this post

Pull data from json and display it in Gridview

$
0
0
I have a ison file http://xxx.com/api/feed/xxxxx.json?multi_brand=1

below is the info...

{
items: [
{
brand: {
tid: "xxx",
name: "xxx",
description: null,
logo: "xxx",
cover: ""
},
nid: "xxx",
title: "xxx",
summary: "xxx ",
social_channel: "xxx",
post_type: "xxx",
url: "xxx",
comment_count: "0",
author: {
profile: "xxx",
name: "xxx",
picture: "xxx"
},
featured: "0",
status: "1",
created: "xxx",
datetime: "xxx",
datetime2: "xxx",
content_type: [ ],
source: {
id: "xx"
},

I need to display some info like NID , Title and etc in grid view. How to i pull the data and display it?

in controller
$data = array();
$data = file_get_contents('http://xxx.com/api/feed/xxxxx.json?multi_brand=1');
$data = json_decode($data, true);

but in view

So how to show it zii.widgets.grid.CGridView?

checked в activeRadioList

$
0
0
Я новичок, поэтому может не догоняю, в общем есть activeRadioList
<?= Html::activeRadioList($model,'db',['MySQL MyISAM' =>'MySQL MyISAM','MySQL InnoDB' =>'MySQL InnoDB','PostgreSQL' =>'PostgreSQL'],['separator' => '<br>']) ?>

Как в нём поставить checked хотя бы на первый элемент?

Вот в Html::radioList checked вообще легко делается, почему в activeRadioList так же не сделали? -__- Вроде можно как-то в itemOptions сделать, но как - не ра3берёшь! Как только не пробовал и в коде про checked - ни слова! -__-
Ссылка на д0ку activeRadioList

OffT0P
До того как здесь написал - написал на yiiframework.ru/forum, но вроде не прошёл модерацию, и вообще по дурацки сделали - не понятно то ли удалили твой топик то ли ещё на модерации! -__- Как всегда - всё для людей!

Require Yii / AWS Developer for Long Term Cotracts

$
0
0
Require a Yii developer to help us create a secure file sharing community app using amazon web services.

Features will include - Virtual private network configuration with scaling, backup and redundancy, instant messaging with file sharing (similar to skype), create user profiles, create private user groups with the ability to search for and invite users (similar to linkedin), create personalized user calendars, security features such as limited time user sessions, SSL and encryption. The system should keep logs of all activity and should be searchable.


You must be familiar with PHP, Yii, Phone gap build, Phone Gap, Amazon Web Services and Security as core skill set.

Selected candidates will be given full details.

Please contact me if interested.

terryp@pixstreammedia.com

Senior PHP Developer \ Team Lead \ CTO for hire

$
0
0
Hello everyone.

My name is Arkadiy and i am looking for new opportunities to challenge my skills.

Some short facts about me:
- I started programming around 20 years ago when i was 15 (Basic, Pascal, C, masm)
- I have 10+ years of experience as a web developer (PHP)
- I spent the last 5 years as a team leader \ CTO in small team with huge highload project (Yii1 \ Yii2)
- Also i have 7+ years of experience in affiliate marketing as an affiliate and advertiser
- All these years i've worked only remotely
- Interested in developing\leading huge, complex projects with wide range of opportunities and responsibilities
- Willing to learn any modern language (mostly interested in Golang, Rust, playing with them already)
- Toying with Unity3D and C#

So, in short, i have experience with: php5, mysql, yii 1\2, js, jquery, boostrap, redis, memcache, couchbase, elasticsearch, sphinx, git workflow, unit tests, codeception, continuous integration, jira, bamboo, stash, confluence, analytics, billing integration, highload optimization, code review, monetization strategies, traffic and income analysis, team leading, linux administration \ devops, etc.

Please notice:
- I am from Saint-Petersburg, Russia but located in Prague, Czech Republic atm
- My rate is pretty high and im looking only for long-term huge projects or\and startups

Feel free to contact me if interested
email: savvot@ya.ru
skype: savvot

Thank you for your attention.
Viewing all 18717 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>