php,symfony2,sonata-admin,symfony-sonata , ReflectionException with Symfony and Sonata, “Class does not exist”


ReflectionException with Symfony and Sonata, “Class does not exist”

Question:

Tag: php,symfony2,sonata-admin,symfony-sonata

I'm experiencing a problem trying to fit my Entities in the Sonata Admin Bundle. I have something like 5 entities, which are finely listed and viewed in the bundle, but I cannot edit or create a new entry.

When I try to edit or create, I get a ReflectionException error:

Class does not exist

I tried in order to solve that problem to operate on namespaces (moving controller in the same namespace that Admin files, or so) or to tweak the Admin Controller in order to tell it about my entities ("->add('individual', 'entity', array('class' => 'Platform\ProjectBundle\Entity\Individual'))" instead of ->add('individual')).

My entity is named Biosample. Here is the Entity file:

<?php

namespace Platform\ProjectBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
* @ORM\Entity
* @ORM\Table(name="biosample")
*/
class Biosample
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
 protected $id;

/**
 * @ORM\ManyToOne(targetEntity="Individual", inversedBy="samples")
 * @ORM\JoinColumn(name="individual_id", referencedColumnName="id")
 */
 protected $individual;

/**
 * @ORM\Column(type="string", length=100)
 */
 protected $organ;

 /**
 * @ORM\Column(type="string", length=100)
 */
 protected $sample_name;

/**
 * @ORM\Column(type="string", nullable=true)
 */
 protected $organ_location;

/**
 * @ORM\Column(type="string")
 */
 protected $tissue_type;

/**
 * @ORM\Column(type="string", nullable=true)
 */
 protected $tissue_subtype;

/**
 * @ORM\Column(type="datetimetz")
 */
 protected $sampling_date;

/**
 * @ORM\Column(type="decimal", scale=3, nullable=true)
 */
 protected $cellularity;

/**
 * @ORM\Column(type="string", nullable=true)
 */
 protected $conservation;

/**
 * @ORM\Column(type="text", nullable=true)
 */
 protected $description;

/**
 * @ORM\ManyToMany(targetEntity="Project", mappedBy="biosamples")
 */
 protected $projects;

 public function __construct()
 {
      $this->projects = new ArrayCollection();
 }

 public function __toString()
 {
      return $this->sample_name;
 }

/**
 * Get id
 *
 * @return integer 
 */

public function getId()
{
    return $this->id;
}

/**
 * Set organ
 *
 * @param string $organ
 * @return Biosample
 */
public function setOrgan($organ)
{
    $this->organ = $organ;

    return $this;
}

/**
 * Get organ
 *
 * @return string 
 */
public function getOrgan()
{
    return $this->organ;
}

/**
 * Set organ_location
 *
 * @param string $organLocation
 * @return Biosample
 */
public function setOrganLocation($organLocation)
{
    $this->organ_location = $organLocation;

    return $this;
}

/**
 * Get organ_location
 *
 * @return string 
 */
public function getOrganLocation()
{
    return $this->organ_location;
}

/**
 * Set tissue_type
 *
 * @param string $tissueType
 * @return Biosample
 */
public function setTissueType($tissueType)
{
    $this->tissue_type = $tissueType;

    return $this;
}

/**
 * Get tissue_type
 *
 * @return string 
 */
public function getTissueType()
{
    return $this->tissue_type;
}

/**
 * Set tissue_subtype
 *
 * @param string $tissueSubtype
 * @return Biosample
 */
public function setTissueSubtype($tissueSubtype)
{
    $this->tissue_subtype = $tissueSubtype;

    return $this;
}

/**
 * Get tissue_subtype
 *
 * @return string 
 */
public function getTissueSubtype()
{
    return $this->tissue_subtype;
}

/**
 * Set sampling_date
 *
 * @param \DateTime $samplingDate
 * @return Biosample
 */
public function setSamplingDate($samplingDate)
{
    $this->sampling_date = $samplingDate;

    return $this;
}

/**
 * Get sampling_date
 *
 * @return \DateTime 
 */
public function getSamplingDate()
{
    return $this->sampling_date;
}

/**
 * Set cellularity
 *
 * @param string $cellularity
 * @return Biosample
 */
public function setCellularity($cellularity)
{
    $this->cellularity = $cellularity;

    return $this;
}

/**
 * Get cellularity
 *
 * @return string 
 */
public function getCellularity()
{
    return $this->cellularity;
}

/**
 * Set conservation
 *
 * @param string $conservation
 * @return Biosample
 */
public function setConservation($conservation)
{
    $this->conservation = $conservation;

    return $this;
}

/**
 * Get conservation
 *
 * @return string 
 */
public function getConservation()
{
    return $this->conservation;
}

/**
 * Set description
 *
 * @param string $description
 * @return Biosample
 */
public function setDescription($description)
{
    $this->description = $description;

    return $this;
}

/**
 * Get description
 *
 * @return string 
 */
public function getDescription()
{
    return $this->description;
}

/**
 * Set individual
 *
 * @param \Platform\ProjectBundle\Entity\Individual $individual
 * @return Biosample
 */
public function setIndividual(\Platform\ProjectBundle\Entity\Individual $individual = null)
{
    $this->individual = $individual;

    return $this;
}

/**
 * Get individual
 *
 * @return \Platform\ProjectBundle\Entity\Individual 
 */
public function getIndividual()
{
    return $this->individual;
}

/**
 * Add projects
 *
 * @param \Platform\ProjectBundle\Entity\Project $projects
 * @return Biosample
 */
public function addProject(\Platform\ProjectBundle\Entity\Project $projects)
{
    $this->projects[] = $projects;

    return $this;
}

/**
 * Remove projects
 *
 * @param \Platform\ProjectBundle\Entity\Project $projects
 */
public function removeProject(\Platform\ProjectBundle\Entity\Project $projects)
{
    $this->projects->removeElement($projects);
}

/**
 * Get projects
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getProjects()
{
    return $this->projects;
}

/**
 * Set sample_name
 *
 * @param string $sampleName
 * @return Biosample
 */
public function setSampleName($sampleName)
{
    $this->sample_name = $sampleName;

    return $this;
}

/**
 * Get sample_name
 *
 * @return string 
 */
public function getSampleName()
{
    return $this->sample_name;
}
}`

Here is my BiosampleAdmin.php:

    <?php

namespace Platform\ProjectBundle\Controller\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;

use Knp\Menu\ItemInterface as MenuItemInterface;

use Platform\ProjectBundle\Entity\Biosample;

class BiosampleAdmin extends Admin
{

    /**
     * @param \Sonata\AdminBundle\Show\ShowMapper $showMapper
     *
     * @return void
     */
    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('id')
            ->add('sample_name')
            ->add('individual', 'entity', array('class' => 'Platform\ProjectBundle\Entity\Individual'))
            ->add('organ')
            ->add('organ_location')
            ->add('tissue_type')
            ->add('tissue_subtype')
            ->add('sampling_date')
            ->add('cellularity')
            ->add('conservation')
            ->add('projects', 'entity', array('class' => 'Platform\ProjectBundle\Entity\Project'))
            ->add('description')
        ;
    }


    /**
     * @param \Sonata\AdminBundle\Form\FormMapper $formMapper
     *
     * @return void
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->with('General')
                ->add('sample_name')
                ->add('individual')
                ->add('organ')
                ->add('organ_location')
                ->add('tissue_type')
                ->add('tissue_subtype')
            ->end()
            ->with('Miscelaneous')
                ->add('sampling_date')
                ->add('cellularity')
                ->add('conservation')
            ->end()
            ->with('Projects')
                ->add('projects')
            ->end()
            ->with('Description')
                ->add('description', 'sonata_type_model', array('multiple' => false))
            ->end()
        ;
    }

    /**
     * @param \Sonata\AdminBundle\Datagrid\ListMapper $listMapper
     *
     * @return void
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('id')
            ->add('sample_name')
            ->add('individual')
            ->add('projects')
            ->add('organ')
            ->add('tissue')
            ->add('_action', 'actions', array(
                'actions' => array(
                    'show' => array(),
                    'edit' => array(),
                    'delete' => array(),
                )
            ))
        ;
    }


    /**
     * @param \Sonata\AdminBundle\Datagrid\DatagridMapper $datagridMapper
     *
     * @return void
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('sample_name')
            ->add('individual')
            ->add('projects')
        ;
    }
}

Here is the admin controller:

    <?php

namespace Platform\ProjectBundle\Controller;

use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Platform\ProjectBundle\Entity\Biosample;

class BiosampleAdminController extends Controller
{

}

And if you need it, here my composer.json:

{
    "name": "symfony/framework-standard-edition",
    "license": "MIT",
    "type": "project",
    "description": "The \"Symfony Standard Edition\" distribution",
    "autoload": {
        "psr-0": { "": "src/", "SymfonyStandard": "app/" }
    },
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "2.6.*",
        "doctrine/orm": "~2.2,>=2.2.3,<2.5",
        "doctrine/dbal": "<2.5",
        "doctrine/doctrine-bundle": "~1.2",
        "twig/extensions": "~1.0",
        "symfony/assetic-bundle": "~2.3",
        "symfony/swiftmailer-bundle": "~2.3",
        "symfony/monolog-bundle": "~2.4",
        "sensio/distribution-bundle": "~3.0,>=3.0.12",
        "sensio/framework-extra-bundle": "~3.0,>=3.0.2",
        "jms/security-extra-bundle": "~1.2",
        "ircmaxell/password-compat": "~1.0.3",
        "stof/doctrine-extensions-bundle": "[email protected]",
        "friendsofsymfony/user-bundle": "~1.3",
        "incenteev/composer-parameter-handler": "~2.0",
        "nervo/yuicompressor": "2.4.8",
        "sonata-project/admin-bundle": "~2.3",
        "sonata-project/doctrine-orm-admin-bundle": "~2.3",
        "sonata-project/easy-extends-bundle": "~2.1",
        "sonata-project/user-bundle": "~2.2",
        "knplabs/knp-menu-bundle": "~1.1",
        "mopa/bootstrap-bundle": "~2",
        "twbs/bootstrap-sass": "~3.3.0",
        "knplabs/knp-paginator-bundle": "dev-master",
        "knplabs/knp-menu": "~1.1",
        "craue/formflow-bundle": "~2.0"
    },
    "require-dev": {
        "sensio/generator-bundle": "~2.3"
    },
    "scripts": {
        "post-root-package-install": [
            "SymfonyStandard\\Composer::hookRootPackageInstall"
        ],
        "post-install-cmd": [
            "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles"
        ],
        "post-update-cmd": [
            "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles"
        ]
    },
    "config": {
        "bin-dir": "bin"
    },
    "extra": {
        "symfony-app-dir": "app",
        "symfony-web-dir": "web",
        "symfony-assets-install": "relative",
        "incenteev-parameters": {
            "file": "app/config/parameters.yml"
        },
        "branch-alias": {
            "dev-master": "2.6-dev"
        }
    }
}

Finally, here's my service declaration and my config.yml file: Service.yml:

services:
    platform.project.admin.biosample:
        class: Platform\ProjectBundle\Controller\Admin\BiosampleAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, group: Project Manager, label: Biosample }
        arguments: [null, Platform\ProjectBundle\Entity\Biosample, PlatformProjectBundle:BiosampleAdmin]

Config.yml:

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }

framework:
    #esi:             ~
    translator:      { fallbacks: ["%locale%"] }
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection: ~
    validation:      { enable_annotations: true }
    templating:
        engines: ['twig']
        #assets_version: SomeVersionScheme
    default_locale:  "%locale%"
    trusted_hosts:   ~
    trusted_proxies: ~
    session:
        # handler_id set to null will use default session handler from php.ini
        handler_id:  ~
    fragments:       ~
    http_method_override: true

# Twig Configuration
twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"

# Assetic Configuration
assetic:
    debug:          "%kernel.debug%"
    use_controller: false
    bundles:        [ ]
    #java: /usr/bin/java
    filters:
        cssrewrite: ~
        #closure:
        #    jar: "%kernel.root_dir%/Resources/java/compiler.jar"
        #yui_css:
        #    jar: "%kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar"

# Doctrine Configuration
doctrine:
    dbal:
        driver:   "%database_driver%"
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8
        # if using pdo_sqlite as your database driver:
        #   1. add the path in parameters.yml
        #     e.g. database_path: "%kernel.root_dir%/data/data.db3"
        #   2. Uncomment database_path in parameters.yml.dist
        #   3. Uncomment next line:
        #     path:     "%database_path%"
        types:
            json: Sonata\Doctrine\Types\JsonType
    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        auto_mapping: true

# Swiftmailer Configuration
swiftmailer:
    transport: "%mailer_transport%"
    host:      "%mailer_host%"
    username:  "%mailer_user%"
    password:  "%mailer_password%"
    spool:     { type: memory }


fos_user:
    db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
    firewall_name: secured
    user_class: Application\Sonata\UserBundle\Entity\User
    group:
        group_class: Application\Sonata\UserBundle\Entity\Group
        group_manager: sonata.user.orm.group_manager

    service:
        user_manager: sonata.user.orm.user_manager


sonata_doctrine_orm_admin:
    entity_manager: ~

sonata_block:
    default_contexts: [cms]
    blocks:
        sonata.admin.block.admin_list:
            contexts: [admin]
        sonata.user.block.menu: ~
        sonata.user.block.account: ~
        sonata.block.service.text: ~


sonata_user:
    security_acl: true
    manager_type: orm

mopa_bootstrap:
    form: ~

And last but not least: the full stack trace.

[1] ReflectionException: Class  does not exist
    at n/a
        in /var/www/Project/app/cache/dev/classes.php line 6756

    at ReflectionClass->__construct('')
        in /var/www/Project/app/cache/dev/classes.php line 6756

    at Doctrine\Common\Persistence\AbstractManagerRegistry->getManagerForClass(null)
        in /var/www/Project/vendor/sonata-project/doctrine-orm-admin-bundle/Model/ModelManager.php line 220

    at Sonata\DoctrineORMAdminBundle\Model\ModelManager->getEntityManager(null)
        in /var/www/Project/vendor/sonata-project/doctrine-orm-admin-bundle/Model/ModelManager.php line 54

    at Sonata\DoctrineORMAdminBundle\Model\ModelManager->getMetadata(null)
        in /var/www/Project/vendor/sonata-project/doctrine-orm-admin-bundle/Model/ModelManager.php line 317

    at Sonata\DoctrineORMAdminBundle\Model\ModelManager->getIdentifierFieldNames(null)
        in /var/www/Project/app/cache/dev/classes.php line 12663

    at Sonata\AdminBundle\Form\ChoiceList\ModelChoiceList->__construct(object(ModelManager), null, null, null, null)
        in /var/www/Project/app/cache/dev/classes.php line 13690

    at Sonata\AdminBundle\Form\Type\ModelType->Sonata\AdminBundle\Form\Type\{closure}(object(OptionsResolver), object(SimpleChoiceList))
        in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/OptionsResolver/OptionsResolver.php line 836

    at Symfony\Component\OptionsResolver\OptionsResolver->offsetGet('choice_list')
        in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/OptionsResolver/OptionsResolver.php line 769

    at Symfony\Component\OptionsResolver\OptionsResolver->resolve(array('sonata_field_description' => object(FieldDescription), 'class' => null, 'model_manager' => object(ModelManager), 'multiple' => false, 'label_render' => false, 'label' => 'Description'))
        in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/Form/ResolvedFormType.php line 109

    at Symfony\Component\Form\ResolvedFormType->createBuilder(object(FormFactory), 'description', array('sonata_field_description' => object(FieldDescription), 'class' => null, 'model_manager' => object(ModelManager), 'multiple' => false, 'label_render' => false, 'label' => 'Description'))
        in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php line 82

    at Symfony\Component\Form\Extension\DataCollector\Proxy\ResolvedTypeDataCollectorProxy->createBuilder(object(FormFactory), 'description', array('sonata_field_description' => object(FieldDescription), 'class' => null, 'model_manager' => object(ModelManager), 'multiple' => false, 'label_render' => false, 'label' => 'Description'))
        in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/Form/FormFactory.php line 87

    at Symfony\Component\Form\FormFactory->createNamedBuilder('description', 'sonata_type_model', null, array('sonata_field_description' => object(FieldDescription), 'class' => null, 'model_manager' => object(ModelManager), 'multiple' => false, 'label_render' => false, 'label' => 'Description'))
        in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/Form/FormBuilder.php line 106

    at Symfony\Component\Form\FormBuilder->create('description', 'sonata_type_model', array('sonata_field_description' => object(FieldDescription), 'class' => null, 'model_manager' => object(ModelManager), 'multiple' => false, 'label_render' => false, 'label' => 'Description'))
        in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/Form/FormBuilder.php line 268

    at Symfony\Component\Form\FormBuilder->resolveChildren()
        in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/Form/FormBuilder.php line 216

    at Symfony\Component\Form\FormBuilder->getForm()
        in /var/www/Project/app/cache/dev/classes.php line 9671

    at Sonata\AdminBundle\Admin\Admin->buildForm()
        in /var/www/Project/app/cache/dev/classes.php line 9930

    at Sonata\AdminBundle\Admin\Admin->getForm()
        in /var/www/Project/vendor/sonata-project/admin-bundle/Controller/CRUDController.php line 353

    at Sonata\AdminBundle\Controller\CRUDController->editAction('1')
        in  line 

    at call_user_func_array(array(object(CRUDController), 'editAction'), array('1'))
        in /var/www/Project/app/bootstrap.php.cache line 3022

    at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), '1')
        in /var/www/Project/app/bootstrap.php.cache line 2984

    at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), '1', true)
        in /var/www/Project/app/bootstrap.php.cache line 3133

    at Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle(object(Request), '1', true)
        in /var/www/Project/app/bootstrap.php.cache line 2377

    at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
        in /var/www/Project/web/app_dev.php line 28

Answer:

Well, the reason for this error was a bad copy/paste from the tutorial.

In the Admin Class, the function configureFormFields contained a field "Description" badly described.

->with('Description')
                ->add('description', 'sonata_type_model', array('multiple' => false))
            ->end()

I had to replace it to:

  ->with('Description')
                ->add('description')
            ->end()

I discovered that automatic Admin Class skeleton generation was a function of Sonata Admin Bundle. In order to automatically generate, execute:

php app/console sonata:admin:generate

Then enter the full path to your entity, in this example:

Platform\ProjectBundle\Entity\Biosample

The admin bundle will parse your entity and :

I guess this should be the prefered method when one is starting with sonata admin bundle.


Related:


Dynamically select from a dynamically generated dropdown


php,html,select,drop-down-menu
I have a dynamically generated dropdown list - list of course identifiers and names. On the basis of a variable, “assigned_course_id”, I would like to preselect the appropriate value from the dropdown list. My best attempt is as follows. Thanks in advance for your assistance. <select name="course_id" id="course_id"> <?php $assigned_course_id...

WooCommerce: How to display Category Name in single-product.php


php,wordpress,woocommerce
How can I display the category name in single-product.php? In archive-product.php the code is: <?php woocommerce_page_title(); ?> but what could I use to show the category name in the single-product.php that belong to the category?...

What are correct permissions for Linux Apache2 PHP 5.3 log file?


php,linux,apache,logging,permissions
I discovered the reason why I was not getting entries into my php_errors.log file related to permissions. Right now, I have set it to 666 (rw-rw-rw-) but surely this is a security weakness? Thus, my question. php.ini file: error_log /var/log/httpd/php_errors.log log_errors On # ls -ld /var/log /var/log/httpd /var/log/httpd/php_errors.log drwxr-xr-x 6...

php include capitalization on files


php
This example works fine on my localhost (both files are included), but on my server only the second one is: <?php include('Test.php'); echo '<br/>'; include('test.php'); ?> The only difference is the caps on the second include, so I was trying to figure out how to make the caps not matter....

WooCommerce seems to only orderby date and not price


php,ajax,wordpress,woocommerce
I am loading in variable products via a custom WP_Query $args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'beast-balls', 'orderby' => 'date', 'order' => 'desc' ); $loop = new WP_Query( $args ); if ( $loop->have_posts() ) { while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="product-node cat-beast-balls">...

Jquery parsley validate not working


javascript,php,jquery,ajax,parsley.js
if($("#dataform").parsley().isValid()){ $.ajax({ url : '<?php echo base_url();?>index.php/company/final_review?id=<?php echo $this->input->get('id'); ?>', type : 'POST', data : $("#dataform").serialize(), dataType:"json", beforeSend: function(){ $('#remarks').parsley( 'addConstraint', { minlength: 5 }); }, success : function(data){ console.log(data); } }); } This is my ajax part. The plugin is not validating the field it's submitting the form. The...

access the json encoded object returned by php in jquery


php,jquery,ajax,json
I want to post some data to php function by ajax, then get the encoded json object that the php function will return, then I want to get the information (keys and values) from this object, but I don't know how, here is my code: $.ajax({ url: "functions.php", dataType: "JSON",...

How to search images by name inside a folder?


php,mysql,image
I have a MySQL table with a column "rounds" and each "rounds" has his own photos. Exemple round1 has photos from start=380 end=385. This means it has 6 photos and the name of the photos contains 380,381,382,383,384 or 385 inside. I use this PHP code to display the photos from...

Wordpress log out using URL and redirect to specify page


javascript,php,wordpress
I have one Wordpress installation . i need to log out the user without any indication user is coming from particular URL.Is it possible? My code: <?php if($_GET['logout'] == 1) { $redirect_to = current_page_url(); ?> <script> window.location.href="<?php echo wp_logout_url( $redirect_to ); ?>"; </script> <?php } ?> I am using above...

compare today's date with unix timestamp value in database


php,mysql
In database I am storing date value unix timestamp value for e.g.'1434952110' using time() now I am trying to compare todays value with this value as below $jobpostdate = date("Y-m-d");//today's date passing in database to compare query $sql = "SELECT jsp_title, jsp_subtitle, jsp_desc, jsp_location, jsp_date "; $sql .= "FROM js_projects...

PHP / MySQLi: How to prevent SQL injection on INSERT (code partially working)


php,mysql,mysqli,sql-injection,sql-insert
I am new to PHP and hope someone can help me with this. I would like to store two values (an email and a password) in a MySQL db using PHP. The input is passed to the PHP page via Ajax in jQuery (through an onclick event on a website)....

Codeigniter PHP Mailer, Sender Info


php,email,codeigniter-2,phpmailer,contact-form
I'm using Codeigniter PHP Mailer which is hosted here: https://github.com/ivantcholakov/codeigniter-phpmailer/ and with gmail smtp it works flawless. However,using it for a standard contact form, when visitors use that contact form and send us an email, they basically send mails from our mail address to our another mail addess. When they...

Symfony 2 unable to pass entity repository to form


php,forms,symfony2,runtime-error
I have a form with a drop down and a set of checkboxes, i've used entity form field type to get the values via DB. it works with one of the entity but not with the other. i have this code seperately inside AddBadgesType there is NO AddBadges entity <?php...

Php Mysql Query not working properly


php,mysql
I have a table name tblnetworkstatus and I have 11 columns Id issue_name affected_server affected_service issue_type priority duration status start_date end_date description I am getting id in affected_server and affected_service which I am storing in my DB, now I have three situations Either both affected_server and affected_service has been selected...

MySQL Query returning strange values


php,mysql
The query is supposed to do the following: Obtain the question and associated answers based on the identification number of the question. (In this case the identification number is called account_id. Order them so that each question (and it's appropriate answers) are lined up in order. The query: SELECT *...

How can I replace the white rectangle within an image using ImageMagick?


php,image-processing,imagemagick
Overview: The first picture is my original image. Here I want to replace the white rectangle shown with another image. My approach: I have created a mask image using floodfill and it looks as: Problem: Now I would like to get the distance or co-ordinates of the rectangle in the...

array and function php


php,arrays
I'm just a beginner in PHP coding. I've been reading through a tutorial, but having some trouble with basic PHP concepts. If you could help me, I'd be much obliged. I'm having trouble understanding why the following code doesn't work. <?php function sum($x, $y) { $z = $x + $y;...

Trying to rewrite mysql_* to pdo


php,mysql,pdo
First of all I should say that I started to learn PDO and trying to rewrite some old mine codes. Here is one that I found on tutorial for a jquery/ajax/pdo/mysql comment system which is working. This is the mysql_* part which I'm trying to rewrite -> file submit.php which...

Wordpress End If Statements


php,wordpress,woocommerce
Apologies, PHP is not my strongest area so this might seem super easy to others. I am trying to implement a statement to say, when there is something in my WooCommerce Cart to show the cart. If there's nothing in the cart then show nothing. The code I have so...

Include both local and server at the same time


php
I have an include statement in my program: include_once("C:/apache2.2/htdocs/AdminTool/includes/functions.php"); //include_once("/var/www/AdminTool/includes/functions.php"); I only use one at a time. In the code above I am using it for my localhost. But if I will run it on server, I have to comment the local one. Because it will cause error. Is there...

mysql_real_escape_string creates \ in server only not in local


php,sql
When I use mysql_real_escape_string in my localhost and I output the result of html in a table I have no problem. But when I use it on my server it outputs even the \ This is how I use it: $_GETVARS['txtEmpNum'] = mysql_real_escape_string($_GETVARS['txtEmpNum']); $_GETVARS['txtLName'] = mysql_real_escape_string($_GETVARS['txtLName']); $_GETVARS['txtFName'] = mysql_real_escape_string($_GETVARS['txtFName']); $varSQL...

Rewrite url not working in htaccess


php,apache,.htaccess,mod-rewrite,url-rewriting
I have website. I just want to rewrite url using .htaccess Here is the code which I want to rewrite: RewriteEngine On RewriteBase / RewriteCond %{QUERY_STRING} /search_data.php\?keywords=([^&]+)&f=([^\s&]+) [NC] RewriteRule ^/search_data.php/?$ /search/%1/%2? [R=301,L,NC] this the current url http://localhost/mywbsite/search_data.php?keywords=one+piece&f=149 I want to convert this to this http://localhost/mywbsite/search/one-piece/149 I tried above code but...

How can we validate multiple fields with one validation in cakePHP 2.0?


php,cakephp
how can we check firstname and last name is unique validation in cakePHP ? record1: first name :raj last name: kumar if we enter same name in input field , it should show validation message "Record alredy Exists". i know how to validate single field validation. how to validate that...

When I click to the next page on pagination,it goes to 404 error in codeigniter


php,codeigniter,pagination
In my News.phpcontroller,i'm having the below code: public function index() { $data['title'] = 'Database Details'; $config = array(); $config['base_url'] = base_url("news/index"); $config['total_rows'] = $this->news_model->record_count(); $config['per_page'] = 5; $config['uri_segment'] = 3; //$config['use_page_numbers'] = TRUE; // $config['page_query_string'] = TRUE; $choice = $config["total_rows"] / $config["per_page"]; $config["num_links"] = round($choice); $this->pagination->initialize($config); $page =...

Laravel 4.2 Sending email error


php,email,laravel,laravel-4
Hello everyone I have an error in laravel when I am sending an email. I have a form with a select tag and when I select the user and click submit I need to send him a mail after I select it. Here is my Controller method: public function store()...

Composer dump-autoload gives preg_match error


php,composer-php,autoload
I have Composer in my PHP project installed, and want to use the autoloader. On this page I read how the composer.json file should look like and that I should run the command dump-autoload. My composer.json file looks as follows { "require-dev":{ "phpunit/phpunit":"4.5.*", "autoload":{ "psr-0":{ "Yii\\":"yii-1.1.14.f0fee9/" } } } }...

How to secure configuration file containing database username and password


php,security
Issue In order to connect my PHP code with MySQL database I use PDO way, creating variable, assigning it with new PDO object where arguments contain settings such as server, database, login and password. So in resulting code it could look like this: $DAcess=new PDO("mysql:host=server;dbname=database","login","password"); I don't feel comfortable having...

Click on link next link should be display on same page


javascript,php,jquery,html,css3
I have a single page website and need to link the navigation to IDs in the page. I have three links: "About us", "Our Project", "contact". So if user clicks on "About ", the About section will be displayed, same with other links. Inside Our project there is Two buttons...

$http.get returns actual php script instead of running it (yeoman, grunt)


php,angularjs,pdo,gruntjs
I'm building a "simple" AngularJS app with an articles newsfeed. My articles are stored in a mysql database, and I extract them using php PDO. I used to do this using AJAX with a simple LAMP configuration (php5, mysql, apache2), and everything worked as intended. Now I'm trying to rebuild...

Cant submit form


javascript,php
Basically I've got a form with 5 radio buttons. No submit button. I want the form to run when the user clicks on any of the radio buttons, so this is what I did. <input id="5" type="radio" name="star" onchange="this.form.submit();" <?php if ($row["star"] =="5") echo "checked";?> value="5"/> a querystring is required...

Why am getting this error?: Unknown column 'firstname' in 'field list'


php,database,mysqli
if(isset($_POST["submit"])) { // Details for inserting into the database $id = htmlentities($_POST["id"]); $firstname = htmlspecialchars($_POST["firstname"]); $lastname = htmlspecialchars($_POST["lastname"]); $username = htmlspecialchars($_POST["username"]); $password = htmlspecialchars($_POST["password"]); // Dealing with inserting $query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, $firstname, $lastname,$username,$password)"; $result = mysqli_query($connection,$query);...

How to register global variable for my Laravel application?


php,laravel,laravel-5
I have started with Laravel a few days ago, and today I just installed the vespakoen/menu that seems to be very nice, and probably will work for what I need it. Currently I have installed Laravel 5.1 on my system. The problem I currently have, is where to register my...

How to pass a value from a page to another page in PHP


php
Im trying to pass a variable value from a page to another page. Im using to go to the next page and I use Session to get the value, the link variable does working but the price variable doesn't work Here's the code: index.php <?php require('connect.php'); if(!isset($_SESSION)){ session_start(); } $query...

How to modify CodeIgniter calendar to handle multiple events per day?


php,codeigniter,calendar
I am creating a calendar without jquery calendar plugin. I could retrieve the data which is in the database to the calendar. But when there are multiple data per day only one data comes to the calendar view. I want it to be like this when there is multiple data....

Time format conversion with PHP


php,time
If have the duration for a recipe in the format 1H10M (1 hour, 10 minutes) or 20M (20 minutes). I want to use the format as described in the parentheses. I've tried using strtotime() without luck. Any help would be greatly appreciated....

How to Match a string with the format: “20959WC-01” in php?


php,regex
i want to restrict a user to enter a value which is similar to the value "20959WC-01", means it must contains 5 integers followed by two character, a '-' and two integers, can anyone please give me a solution to sort out this problem. Thanks in advance :) ...

how to multiply two column names using codeigniter validation rule


php,codeigniter,validation
I have three columns.The product of two columns get into third column name income_amount using codeigniter validation rule.the first column is crop_quantity and the second is per_rate controller $this->form_validation->set_rules('crop_quantity', 'Crop Quantity', 'required|numeric'); $this->form_validation->set_rules('per_rate', 'Per Rate', 'required|numeric|callback_get_product'); $this->form_validation->set_rules('income_amount', 'Income Amount', 'required|numeric');...

PHP Regular Expressions Counting starting consonants in a string


php,regex
I need to find out how many starting consonants a word has. The number is used later in the program. The code below does work, I am wondering if it is possible to do this with a regular expression. $mystring ="SomeStringExample"; $mystring2 =("bcdfghjklmnpqrstvwxyzABCDFGHJKLMNPQRSTWVXYZ"); $var = strspn($mystring, $mystring2); Using a regular...

Laravel Interfaces


php,laravel,interface,namespaces
I used the following tutorial to get an idea about interfaces: http://vegibit.com/what-is-a-laravel-interface/ But I wanted to change the directory of where I am putting my interfaces to "App/Models/Interfaces". And so I did. But now I cannot get it to work anymore. Here is my code: Routes.php App::bind('CarInterface', 'Subaru'); Route::get('subaru', function()...

Pull information from SQL database and getting login errors


php,sql,database
I am creating a very small, simple CRM for a company, they require the function to be able to view the last 25 orders via the dashboard. The orders are added via a Order-add form within the CRM. When adding the following code to the CRM I get an error:...

php redirection working in chorme but not on firefox


php,google-chrome,mozilla
Below is my php code that caries out the redirection Code Snippet :- echo "<form action='exp_yogesh.php?id=$id' method='post'>"; echo "<td> <input type='image' name='putonline' value='$id' src='images/on_button.png' no-repeat; border:none;' alt='submit'> </td> "; echo "<td> <input type='image' name='putoffline' value='$id' src='images/off_botton.png' no-repeat; border:none;' alt='submit'> </td> "; echo "</form>"; Here's the exp_yogesh.php file <?php include 'includes/connection.php';...

RecursiveIteratorIterator to fetch subdirectories


php
Currently I am working with directories through php. I am able to list subdirectories for any given directory. However, the results are not 100% what I am looking for. The below code returns subdirectories but in addition it also returns the main directory in the array. How can I only...

How do I display my mysql table column headers in my php/html output?


php,html,mysql,table,data
2 Questions... Scenario: I would like to query my database table via a form and then display the results that occur(if there are results) and my current situation is that it does work but it clears the form completely and leaves my to an empty page with just the results...

Is it a good practise store the checkout steps fields in php $_SESSION?


php,session,e-commerce,checkout
I have my e-commerce site with three checkout steps, each button to continue is a POST action and redirect to the next step: if the user navigates by the checkout steps (click on the previous button for example), the form fields don´t show the data posted previously. This form fields...

Mixing


php
This question already has an answer here: <? ?> tags not working in php 5.3.1 5 answers I had to made some changes to an old PHP-Project (with very poor code quality...) which runs on an PHP 5.3 server. So I've downloaded the project and tried to run it...

Unable to configure Symfony (3rd party) bundle


php,symfony2,rss
I am faily new to Symfony and I am trying to setup a third party bundle that reads RSS feeds and then insert them into database. The third party bundle I am trying to use is called rss-atom-bundle After reading the instructions I can get the RSS feeds however I...

how to escape php code in echo with javascript


javascript,php
how can i escape this : var tab_mois_nb_match = <?php ".json_encode($tab_mois_nb_match)." ;?> ; I have an code error, but the arrays are generate with sussess in the conle.log, it's totally crazy. foreach($tab_bases2 as $key => $univers){ $tab_nb_match_par_user = users_nb_match($univers); $tab_mois_nb_match = mois_nb_match($univers); echo "<div id='".$univers."' ></div>"; echo "<script type='text/JavaScript'> var...

Error connecting to MSSQL using PHP


php,sql-server,pdo,odbc,sqlsrv
I am receiving an error as below: PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]SQL Server Network Interfaces: Connection string is not valid [87]. ' My codes are as follow: $this->link = new PDO( "sqlsrv:server=$this->serverName:$this->port;Database=$this->db", "$this->uid", "$this->pwd" ); I wish someone can enlighten...