how to check already exist entry in database - yii

My default controller function
public function actionAddNewCategories() {
$model = new AddNewCategory();
$model->category_name=strip_tags(trim($_POST['categoryname']));
$model->category_description=strip_tags(trim($_POST['categorydescription']));
$model->save(false);
$category_list=Invoice::getCategoryName();
$test="";
$test = ' <option value="">Select Category</option>';
foreach($category_list as $value ){
$test .= "<option >{$value['category_name']}</option>";
}
echo $test;
}
Model function
public function getCategoryName() {
$id = Yii::app()->db->createCommand()
->select('category_name')
->from('add_new_category c')
->queryAll();
return $id;
}

You can add unique rule into your AddNewCategory model like below:
array('fieldName','unique','className'=>__CLASS__,'attributeName'=>'columnName','allowEmpty'=>FALSE)
By now, You have a rule, which denies to insert new record with existing value.
Another alternative way would be using exist() like below:
$exist=AddNewCategory::model()->exist(array('columnName'=>'VALUE'));
Which $exist variable holds a Boolean value which means whether a record exists with entered condition or not.
http://www.yiiframework.com/doc/api/1.1/CUniqueValidator
http://www.yiiframework.com/doc/api/1.1/CActiveRecord#exists-detail

Related

Prestashop 1.6 CustomerAccountForm

I created my payment module. During module's instalation i'm creating new table ps_mymodule_card with id, customer_id and card_number fields.
In register page I added new text input (card_nubmer) in account register page using hookCreateAccountForm() in module. It displays proper but how to get customer id in function hookCreateAccount($params) inside my payment module? I want to add own post data to database during (or just after) user register .
modules/mypaymentmodule/mypaymentmodule.php
public function hookCreateAccountForm()
{
return '<!--new field in form-->'
. '<div class="form-group">'
. '<label for="card_number">'
. 'Card number:'
. '</label>'
. '<input class="form-control" id="card_number" type="text" name="card_number">'
. '</div>'
. '<!--new field in form-->';
}
public function hookCreateAccount($params)
{
[here put some validation of data]
$cadrNumber = $params['_POST']['card_number'];
$customer = $params['newCustomer'];
$db = Db::getInstance();
$query = 'INSERT INTO `'._DB_PREFIX_.'mymodule_card`
(`customer_id`, `card_number`)
VALUES
("'.intval($customer->id).'", "'. intval($cadrNumber).'")';
$db->Execute($query);
}
function below is calling of course during module instalation!
private function _createMymoduleCardTbl()
{
$db = Db::getInstance();
$query = "CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."mymodule_card` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`customer_id` INT NOT NULL ,
`card_number` TEXT NOT NULL
) ENGINE = MYISAM ";
$db->Execute($query);
return TRUE;
}
do not forget about hooks registering in install method!!
$this->registerHook('createAccountForm')
$this->registerHook('createAccount')

Sylius: How to sort product by variant.sku

I would like to sort the products by its sku. How would that be possible ?
I tried to add in ProductRepository.php:
...
$queryBuilder = $this->getCollectionQueryBuilder();
$queryBuilder
->innerJoin('product.taxons', 'taxon')
->innerJoin('product.variants', 'variant')
->andWhere('taxon = :taxon')
->setParameter('taxon', $taxon)
;
foreach ($criteria as $attributeName => $value) {
$queryBuilder
->andWhere('product.'.$attributeName.' IN (:'.$attributeName.')')
->setParameter($attributeName, $value)
;
}
$queryBuilder->orderBy('variant.sku');
...
but got:
Cannot select distinct identifiers from query with LIMIT and ORDER BY
on a column from a fetch joined to-many association. Use output
walkers.
Finally what I did: Sorted the products just before output in a custom twig function:
macros.html.twig
{% set products = skusort(products) %}
In my SkusortExtenstion.php (as of PHP 5.3)
$product->getIterator()->uasort(function($a, $b){
return $a->getMasterVariant()->getSku() > $b->getMasterVariant()->getSku();
});
return $product;
Was afraid of performance issue as there's a lot of products but seems to be very fast.
Another way is to reload method getPaginator() of class Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository. In that case we must instantinate DoctrineORMAdapter with $useOutputWalkers flag (the latest constructor argument).
So, put the folowing code in your ProductRepository.php:
/**
* {#inheritdoc}
*/
public function getPaginator(QueryBuilder $queryBuilder)
{
return new Pagerfanta(new DoctrineORMAdapter($queryBuilder, true, true));
}

How to get multiple POST data?

I am trying to get the $_POST data from some inputs fields, but the thing is I am getting the number of fields from my database:
$query2 = $DB->prepare("SELECT * FROM params WHERE modulid = $parameterid");
$query2->execute();
<td>Parameter unit:</td>
<?php while (($row2 = $query2->fetch()) != false)
{
$unit = $row2->name;
?><td><input type="text" name="<?php echo $row2->id; ?>" value="<?php echo $unit; ?>" class="textbox"></td><?php
}
?>
What is the code to get post data from all of them so I can update the database if the user wants to type new data in the input?
You can get all values submitted by a form by iterating through the following global variable:
$_POST
By using a foreach loop, you can then check which values were filled and generate an UPDATE SQL statement with them.
Example to get all non-empty values:
$changed = array();
foreach($_POST as $key => $value) {
if(!empty($value)) {
$changed[$key] = $value;
}
}
Then create the query using the $changed array.
Why don't you do something like that
$temp=$row2->id;
mysql_query("insert into params (modulid) values ('$temp')");

limit email domain - vaidation yii

I have email field in signup form ,
I want to validate email domain with database e.g
Email adress is : example#work.com or etc#etc.com
Now I want validate that work.com or etc.com is listed in db or not , if not then it should not be vaidate.!
Can Anyone help me with this ?
Code:
public function validate($attributes = null, $clearErrors = true) {
parent::validate($attributes, $clearErrors);
if (!$this->hasErrors('email')) {
$a = explode('#', $this->email);
if (isset($a[1])) {
$record = AllowedDomains::model()->findByAttributes(array('domain'=>$a[1]));
if ($record === null) {
$this->addError('email', "This domain isn't allowed");
}
}
}
return !$this->hasErrors();
}
Notes:
put this code in the model
email - the field holding the email address
AllowedDomains - the CActiveRecord of the table that holds the allowed domains
domain - replace with the correct database field
don't forget to add the e-mail validator in the rules() function. This will filter out invalid email addresses and the above code will not run if something's wrong
You could accomplish this by adding a custom yii validator in the rules section of your Model. Here is some example code:
public $email; // This is the field where the email is stored
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
return array(
array('email', 'checkDomain'),
);
}
Afterwards, you can add the custom validation function
public function checkDomain($attribute,$params)
{
$sEmailDomain = substr(strrchr($this->email, "#"), 1);
// Check if the domain exists
...
// If the domain exists, add the error
$this->addError('email', 'Domain already exists in the database');
}
More information can be found here: http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/

Yii: adding custom fields

Is there a simple way of adding custom fields to a model? Say I have a table "user" with 3 fields: id, name and surname. I want this:
$user = User::model()->findByPk(1);
$echo $user->fullName; // echoes name and surname
Please note: I want this custom field to be added via sql, smth like
$c = new CDbCriteria();
$c->select = 'CONCAT("user".name, "user".surname) as fullName';
$user = User::model()->find($c);
Problem is that fullName property is not set.
UPD:
here is the code for a little bit trickier problem -- custom field from another table. This is how it's done:
$model = Application::model();
$model->getMetaData()->columns = array_merge($model->getMetaData()->columns, array('fullName' => 'CONCAT("u".name, "u".surname)'));
$c = new CDbCriteria();
$c->select = 'CONCAT("u".name, "u".surname) as fullName';
$c->join = ' left join "user" "u" on "t".responsible_manager_id = "u".id';
$model->getDbCriteria()->mergeWith($c);
foreach ($model->findAll() as $o) {
echo '<pre>';
print_r($o->fullName);
echo '</pre>';
}
You can add a function to the User class:
public function getFullName() { return $this->name.' '.$this->surname; }
This will return the full name as if it were an attribute from the database. This is much easier than adding a calculated column to the SQL.
In model
public function getMetaData(){
$data = parent::getMetaData();
$data->columns['fullName'] = array('name' => 'fullName');
return $data;
}
Thus not recommended